SlideShare uma empresa Scribd logo
1 de 48
MySQL native driver for PHP: Customizing the query cache
mysqlnd_qc:  Customization by user defined storage handler Ulf Wendel, Andrey Hristov MySQL Connectors Team Sun Microsystems
Table of Contents ,[object Object]
Flavours of user handler ,[object Object],[object Object]
Registration ,[object Object],[object Object]
Master class: slam defense
Breaking the limits ,[object Object]
Filter by content, run or store time, result set size ,[object Object],[object Object]
Scope ,[object Object],[object Object],[object Object]
Template Method pattern, kind of Core: invariant part of the caching, handler: variant part <?php  /* Any PHP MySQL application */  ?> ext/*mysql* ext/*mysql* mysqlnd mysqlnd Query Cache Plugin (mysqlnd_qc core) Storage handler (mysqlnd_qc)
Variant and invariant parts (Miss/Put) mysqlnd Cache Plugin handler Cache Plugin core query()  Should cache? Is cached? Activate data recorder Call original query() Deactivate recorder Cache wire data is_select() Want to cache statement? find() Available? TTL? Slam defense? Statistics? add() Run time? Data size? Replacement strategy?
Redefine everything or selected parts ,[object Object]
Full control through new user handler ,[object Object]
OOP: interface mysqlnd_qc_handler ,[object Object],[object Object]
No other build-in handler exported as user class ,[object Object]
Table of Contents ,[object Object]
Flavours of user handler ,[object Object],[object Object]
Registration ,[object Object],[object Object]
Master class: slam defense
Handler API overview ,[object Object]
find_in_cache($key)
return_to_cache($key)
add_to_cache($key, $data, $ttl, $run_t, ...)
is_select($query)
update_stats($key, $run_t, $store_t)
get_stats()
clear_cache()
init()*, shutdown()*
Handler API – Cache Put (I) Application Cache Plugin handler Cache Plugin core *query()  Should cache? Yes! Cache entry 'key'? is_select(...)  a) Don't cache - return: false b) Cache it – return: int TTL get_hash_key(...)  Return key of cache entry. find_in_cache(...) Returns NULL because not found. Do we have 'key'?
Handler API – Cache Put (II) Application Cache Plugin handler Cache Plugin core *query() add_to_cache(...) Add to cache if not exists. Return true if added, false if already in cache. Activate data recorder Call original query() Deactivate recorder Cache wire data *store _result() (often implicit)
Handler API – Cache Hit (I) Application Cache Plugin handler Cache Plugin core *query()  Should cache? Yes! Cache entry 'key'? is_select(...)  a) Don't cache - return: false b) Cache it – return: int TTL get_hash_key(...)  Return key of cache entry. find_in_cache(...) Search cache entry, check if still valid, return cache entry. Do we have 'key'?
Handler API – Cache Hit (II) Application Cache Plugin handler Cache Plugin core *store _result() (often implicit) Client served! Record timings! return_to_cache(...) Cache entry no longer in use by core. (Default needs this) update_stats(...) Run and store time recorded and reported by the core, useful for per-entry stats.
Handler API – Cache Miss (I) Application Cache Plugin handler Cache Plugin core *query()  Should cache? No! is_select(...)  a) Don't cache – return: false b) Cache - see Cache Put (I)
API details - get_hash_key(...) ,[object Object]
string $port – MySQL Server port
string $user – MySQL user
string $db – MySQL data base
string $query – SQL statement ,[object Object]
API details – get_hash_key(...)* pitfall ,[object Object]
string $port – MySQL Server port
string $user – MySQL user
string $db – MySQL data base
string $query – SQL statement
bool $persistent – Flag persistent connection ,[object Object]
API details - find_in_cache(...) ,[object Object]
This is an ideal place to check not only if a cache entry is available but also to implement tife-to-life (TTL) checks or slam defense logic.
For example, if you can find the cache entry but it has expired, you should return NULL to trigger a  cache miss.
API details - find_in_cache(...) ,[object Object]

Mais conteúdo relacionado

Mais procurados

Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGMatthew McCullough
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)MongoDB
 
PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)Nikita Popov
 
Integrating icinga2 and the HashiCorp suite
Integrating icinga2 and the HashiCorp suiteIntegrating icinga2 and the HashiCorp suite
Integrating icinga2 and the HashiCorp suiteBram Vogelaar
 
21.04.2016 Meetup: Spark vs. Flink
21.04.2016 Meetup: Spark vs. Flink21.04.2016 Meetup: Spark vs. Flink
21.04.2016 Meetup: Spark vs. FlinkComsysto Reply GmbH
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebookguoqing75
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineJason Terpko
 
Esprima - What is that
Esprima - What is thatEsprima - What is that
Esprima - What is thatAbhijeet Pawar
 
Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)James Titcumb
 
A miało być tak... bez wycieków
A miało być tak... bez wyciekówA miało być tak... bez wycieków
A miało być tak... bez wyciekówKonrad Kokosa
 
Raquel Guimaraes- Third party infrastructure as code
Raquel Guimaraes-  Third party infrastructure as codeRaquel Guimaraes-  Third party infrastructure as code
Raquel Guimaraes- Third party infrastructure as codeThoughtworks
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsMongoDB
 
Using Spark to Load Oracle Data into Cassandra
Using Spark to Load Oracle Data into CassandraUsing Spark to Load Oracle Data into Cassandra
Using Spark to Load Oracle Data into CassandraJim Hatcher
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query OptimizationMongoDB
 
Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Nikita Popov
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?Nikita Popov
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query OptimizationMongoDB
 

Mais procurados (20)

Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUG
 
Workshop unittesting
Workshop unittestingWorkshop unittesting
Workshop unittesting
 
Perl object ?
Perl object ?Perl object ?
Perl object ?
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)
 
PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)
 
Integrating icinga2 and the HashiCorp suite
Integrating icinga2 and the HashiCorp suiteIntegrating icinga2 and the HashiCorp suite
Integrating icinga2 and the HashiCorp suite
 
21.04.2016 Meetup: Spark vs. Flink
21.04.2016 Meetup: Spark vs. Flink21.04.2016 Meetup: Spark vs. Flink
21.04.2016 Meetup: Spark vs. Flink
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation Pipeline
 
Esprima - What is that
Esprima - What is thatEsprima - What is that
Esprima - What is that
 
Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)
 
A miało być tak... bez wycieków
A miało być tak... bez wyciekówA miało być tak... bez wycieków
A miało być tak... bez wycieków
 
Raquel Guimaraes- Third party infrastructure as code
Raquel Guimaraes-  Third party infrastructure as codeRaquel Guimaraes-  Third party infrastructure as code
Raquel Guimaraes- Third party infrastructure as code
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
Php Security
Php SecurityPhp Security
Php Security
 
Using Spark to Load Oracle Data into Cassandra
Using Spark to Load Oracle Data into CassandraUsing Spark to Load Oracle Data into Cassandra
Using Spark to Load Oracle Data into Cassandra
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
 
Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
 

Destaque

10 things you might not know about MySQL
10 things you might not know about MySQL10 things you might not know about MySQL
10 things you might not know about MySQLJorge Bernal
 
Criterios de admision en terapia intensiva
Criterios de admision en terapia intensivaCriterios de admision en terapia intensiva
Criterios de admision en terapia intensivaRuth Pesina
 
Cuidados de enfermería en la administración de surfactante
Cuidados de enfermería en la administración de surfactanteCuidados de enfermería en la administración de surfactante
Cuidados de enfermería en la administración de surfactanteOscar Gonzalez
 
Gear6 Webinar - MySQL Scaling with Memcached
Gear6 Webinar - MySQL Scaling with MemcachedGear6 Webinar - MySQL Scaling with Memcached
Gear6 Webinar - MySQL Scaling with MemcachedGear6
 
클라우드 서버를 이용한 모바일 웹 개발
클라우드 서버를 이용한 모바일 웹 개발클라우드 서버를 이용한 모바일 웹 개발
클라우드 서버를 이용한 모바일 웹 개발Kenu, GwangNam Heo
 
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016Amazon Web Services Korea
 
Easy MySQL Replication Setup and Troubleshooting
Easy MySQL Replication Setup and TroubleshootingEasy MySQL Replication Setup and Troubleshooting
Easy MySQL Replication Setup and TroubleshootingBob Burgess
 
MySQL Tuning using digested slow-logs
MySQL Tuning using digested slow-logsMySQL Tuning using digested slow-logs
MySQL Tuning using digested slow-logsBob Burgess
 
Performance Schema in MySQL (Danil Zburivsky)
Performance Schema in MySQL (Danil Zburivsky)Performance Schema in MySQL (Danil Zburivsky)
Performance Schema in MySQL (Danil Zburivsky)Ontico
 
The care and feeding of a MySQL database
The care and feeding of a MySQL databaseThe care and feeding of a MySQL database
The care and feeding of a MySQL databaseDave Stokes
 
PoC: Using a Group Communication System to improve MySQL Replication HA
PoC: Using a Group Communication System to improve MySQL Replication HAPoC: Using a Group Communication System to improve MySQL Replication HA
PoC: Using a Group Communication System to improve MySQL Replication HAUlf Wendel
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimizationBaohua Cai
 
MySQL Group Replication
MySQL Group ReplicationMySQL Group Replication
MySQL Group ReplicationUlf Wendel
 
Modern MySQL Monitoring and Dashboards.
Modern MySQL Monitoring and Dashboards.Modern MySQL Monitoring and Dashboards.
Modern MySQL Monitoring and Dashboards.Mydbops
 
Best Practices in Migrating to MySQL - Part 1
Best Practices in Migrating to MySQL - Part 1Best Practices in Migrating to MySQL - Part 1
Best Practices in Migrating to MySQL - Part 1Ronald Bradford
 

Destaque (20)

10 things you might not know about MySQL
10 things you might not know about MySQL10 things you might not know about MySQL
10 things you might not know about MySQL
 
Criterios de admision en terapia intensiva
Criterios de admision en terapia intensivaCriterios de admision en terapia intensiva
Criterios de admision en terapia intensiva
 
Cuidados de enfermería en la administración de surfactante
Cuidados de enfermería en la administración de surfactanteCuidados de enfermería en la administración de surfactante
Cuidados de enfermería en la administración de surfactante
 
Gear6 Webinar - MySQL Scaling with Memcached
Gear6 Webinar - MySQL Scaling with MemcachedGear6 Webinar - MySQL Scaling with Memcached
Gear6 Webinar - MySQL Scaling with Memcached
 
클라우드 서버를 이용한 모바일 웹 개발
클라우드 서버를 이용한 모바일 웹 개발클라우드 서버를 이용한 모바일 웹 개발
클라우드 서버를 이용한 모바일 웹 개발
 
My sql102
My sql102My sql102
My sql102
 
Mysql basics1
Mysql basics1Mysql basics1
Mysql basics1
 
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016
관계형 데이터베이스의 새로운 패러다임 Amazon Aurora :: 김상필 :: AWS Summit Seoul 2016
 
Cb08 sanchez citlali.ppsx
Cb08 sanchez citlali.ppsxCb08 sanchez citlali.ppsx
Cb08 sanchez citlali.ppsx
 
Easy MySQL Replication Setup and Troubleshooting
Easy MySQL Replication Setup and TroubleshootingEasy MySQL Replication Setup and Troubleshooting
Easy MySQL Replication Setup and Troubleshooting
 
MySQL Tuning using digested slow-logs
MySQL Tuning using digested slow-logsMySQL Tuning using digested slow-logs
MySQL Tuning using digested slow-logs
 
Performance Schema in MySQL (Danil Zburivsky)
Performance Schema in MySQL (Danil Zburivsky)Performance Schema in MySQL (Danil Zburivsky)
Performance Schema in MySQL (Danil Zburivsky)
 
MySQL database
MySQL databaseMySQL database
MySQL database
 
The care and feeding of a MySQL database
The care and feeding of a MySQL databaseThe care and feeding of a MySQL database
The care and feeding of a MySQL database
 
PoC: Using a Group Communication System to improve MySQL Replication HA
PoC: Using a Group Communication System to improve MySQL Replication HAPoC: Using a Group Communication System to improve MySQL Replication HA
PoC: Using a Group Communication System to improve MySQL Replication HA
 
Mysql query optimization
Mysql query optimizationMysql query optimization
Mysql query optimization
 
MySQL Group Replication
MySQL Group ReplicationMySQL Group Replication
MySQL Group Replication
 
MySQL DBA
MySQL DBAMySQL DBA
MySQL DBA
 
Modern MySQL Monitoring and Dashboards.
Modern MySQL Monitoring and Dashboards.Modern MySQL Monitoring and Dashboards.
Modern MySQL Monitoring and Dashboards.
 
Best Practices in Migrating to MySQL - Part 1
Best Practices in Migrating to MySQL - Part 1Best Practices in Migrating to MySQL - Part 1
Best Practices in Migrating to MySQL - Part 1
 

Semelhante a MySQL native driver for PHP: Customizing the query cache with user defined storage handlers

Built-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsBuilt-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsUlf Wendel
 
Mysqlnd query cache plugin statistics and tuning
Mysqlnd query cache plugin statistics and tuningMysqlnd query cache plugin statistics and tuning
Mysqlnd query cache plugin statistics and tuningUlf Wendel
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate NotesKaniska Mandal
 
CodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory laneCodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory laneMaarten Balliauw
 
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management....NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...NETFest
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationsourabh aggarwal
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETMaarten Balliauw
 
MUC - Moodle Universal Cache
MUC - Moodle Universal CacheMUC - Moodle Universal Cache
MUC - Moodle Universal CacheTim Hunt
 
Things you can find in the plan cache
Things you can find in the plan cacheThings you can find in the plan cache
Things you can find in the plan cachesqlserver.co.il
 
Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009hugowetterberg
 
idea: talk about the Active Cache
idea: talk about the Active Cacheidea: talk about the Active Cache
idea: talk about the Active CacheChing Yi Chan
 
Instrumenting plugins for Performance Schema
Instrumenting plugins for Performance SchemaInstrumenting plugins for Performance Schema
Instrumenting plugins for Performance SchemaMark Leith
 
Caching with Memcached and APC
Caching with Memcached and APCCaching with Memcached and APC
Caching with Memcached and APCBen Ramsey
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance毅 吕
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestPavan Chitumalla
 
Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Maarten Balliauw
 
Mysqlnd, an unknown powerful PHP extension
Mysqlnd, an unknown powerful PHP extensionMysqlnd, an unknown powerful PHP extension
Mysqlnd, an unknown powerful PHP extensionjulien pauli
 

Semelhante a MySQL native driver for PHP: Customizing the query cache with user defined storage handlers (20)

Built-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsBuilt-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIs
 
Mysqlnd query cache plugin statistics and tuning
Mysqlnd query cache plugin statistics and tuningMysqlnd query cache plugin statistics and tuning
Mysqlnd query cache plugin statistics and tuning
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
 
CodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory laneCodeStock - Exploring .NET memory management - a trip down memory lane
CodeStock - Exploring .NET memory management - a trip down memory lane
 
Performance Tuning
Performance TuningPerformance Tuning
Performance Tuning
 
Dapper performance
Dapper performanceDapper performance
Dapper performance
 
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management....NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
 
DotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NETDotNetFest - Let’s refresh our memory! Memory management in .NET
DotNetFest - Let’s refresh our memory! Memory management in .NET
 
MUC - Moodle Universal Cache
MUC - Moodle Universal CacheMUC - Moodle Universal Cache
MUC - Moodle Universal Cache
 
Things you can find in the plan cache
Things you can find in the plan cacheThings you can find in the plan cache
Things you can find in the plan cache
 
Smarty
SmartySmarty
Smarty
 
Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009
 
idea: talk about the Active Cache
idea: talk about the Active Cacheidea: talk about the Active Cache
idea: talk about the Active Cache
 
Instrumenting plugins for Performance Schema
Instrumenting plugins for Performance SchemaInstrumenting plugins for Performance Schema
Instrumenting plugins for Performance Schema
 
Caching with Memcached and APC
Caching with Memcached and APCCaching with Memcached and APC
Caching with Memcached and APC
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)Exploring .NET memory management (iSense)
Exploring .NET memory management (iSense)
 
Mysqlnd, an unknown powerful PHP extension
Mysqlnd, an unknown powerful PHP extensionMysqlnd, an unknown powerful PHP extension
Mysqlnd, an unknown powerful PHP extension
 

Mais de Ulf Wendel

HTTP Plugin for MySQL!
HTTP Plugin for MySQL!HTTP Plugin for MySQL!
HTTP Plugin for MySQL!Ulf Wendel
 
Data massage: How databases have been scaled from one to one million nodes
Data massage: How databases have been scaled from one to one million nodesData massage: How databases have been scaled from one to one million nodes
Data massage: How databases have been scaled from one to one million nodesUlf Wendel
 
MySQL 5.7 clustering: The developer perspective
MySQL 5.7 clustering: The developer perspectiveMySQL 5.7 clustering: The developer perspective
MySQL 5.7 clustering: The developer perspectiveUlf Wendel
 
MySQL 5.7 Fabric: Introduction to High Availability and Sharding
MySQL 5.7 Fabric: Introduction to High Availability and Sharding MySQL 5.7 Fabric: Introduction to High Availability and Sharding
MySQL 5.7 Fabric: Introduction to High Availability and Sharding Ulf Wendel
 
DIY: A distributed database cluster, or: MySQL Cluster
DIY: A distributed database cluster, or: MySQL ClusterDIY: A distributed database cluster, or: MySQL Cluster
DIY: A distributed database cluster, or: MySQL ClusterUlf Wendel
 
NoSQL in MySQL
NoSQL in MySQLNoSQL in MySQL
NoSQL in MySQLUlf Wendel
 
Vote NO for MySQL
Vote NO for MySQLVote NO for MySQL
Vote NO for MySQLUlf Wendel
 
PHP mysqlnd connection multiplexing plugin
PHP mysqlnd connection multiplexing pluginPHP mysqlnd connection multiplexing plugin
PHP mysqlnd connection multiplexing pluginUlf Wendel
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLHTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLUlf Wendel
 
MySQL? Load? Clustering! Balancing! PECL/mysqlnd_ms 1.4
MySQL? Load? Clustering! Balancing! PECL/mysqlnd_ms 1.4MySQL? Load? Clustering! Balancing! PECL/mysqlnd_ms 1.4
MySQL? Load? Clustering! Balancing! PECL/mysqlnd_ms 1.4Ulf Wendel
 
MySQL 5.6 Global Transaction IDs - Use case: (session) consistency
MySQL 5.6 Global Transaction IDs - Use case: (session) consistencyMySQL 5.6 Global Transaction IDs - Use case: (session) consistency
MySQL 5.6 Global Transaction IDs - Use case: (session) consistencyUlf Wendel
 
MySQL 5.6 Global Transaction Identifier - Use case: Failover
MySQL 5.6 Global Transaction Identifier - Use case: FailoverMySQL 5.6 Global Transaction Identifier - Use case: Failover
MySQL 5.6 Global Transaction Identifier - Use case: FailoverUlf Wendel
 
MySQL native driver for PHP (mysqlnd) - Introduction and overview, Edition 2011
MySQL native driver for PHP (mysqlnd) - Introduction and overview, Edition 2011MySQL native driver for PHP (mysqlnd) - Introduction and overview, Edition 2011
MySQL native driver for PHP (mysqlnd) - Introduction and overview, Edition 2011Ulf Wendel
 
PHPopstar der PHP Unconference 2011
PHPopstar der PHP Unconference 2011PHPopstar der PHP Unconference 2011
PHPopstar der PHP Unconference 2011Ulf Wendel
 
The mysqlnd replication and load balancing plugin
The mysqlnd replication and load balancing pluginThe mysqlnd replication and load balancing plugin
The mysqlnd replication and load balancing pluginUlf Wendel
 
Award-winning technology: Oxid loves the query cache
Award-winning technology: Oxid loves the query cacheAward-winning technology: Oxid loves the query cache
Award-winning technology: Oxid loves the query cacheUlf Wendel
 
The power of mysqlnd plugins
The power of mysqlnd pluginsThe power of mysqlnd plugins
The power of mysqlnd pluginsUlf Wendel
 
Mysqlnd query cache plugin benchmark report
Mysqlnd query cache plugin benchmark reportMysqlnd query cache plugin benchmark report
Mysqlnd query cache plugin benchmark reportUlf Wendel
 
The PHP mysqlnd plugin talk - plugins an alternative to MySQL Proxy
The PHP mysqlnd plugin talk - plugins an alternative to MySQL ProxyThe PHP mysqlnd plugin talk - plugins an alternative to MySQL Proxy
The PHP mysqlnd plugin talk - plugins an alternative to MySQL ProxyUlf Wendel
 
Mysqlnd Async Ipc2008
Mysqlnd Async Ipc2008Mysqlnd Async Ipc2008
Mysqlnd Async Ipc2008Ulf Wendel
 

Mais de Ulf Wendel (20)

HTTP Plugin for MySQL!
HTTP Plugin for MySQL!HTTP Plugin for MySQL!
HTTP Plugin for MySQL!
 
Data massage: How databases have been scaled from one to one million nodes
Data massage: How databases have been scaled from one to one million nodesData massage: How databases have been scaled from one to one million nodes
Data massage: How databases have been scaled from one to one million nodes
 
MySQL 5.7 clustering: The developer perspective
MySQL 5.7 clustering: The developer perspectiveMySQL 5.7 clustering: The developer perspective
MySQL 5.7 clustering: The developer perspective
 
MySQL 5.7 Fabric: Introduction to High Availability and Sharding
MySQL 5.7 Fabric: Introduction to High Availability and Sharding MySQL 5.7 Fabric: Introduction to High Availability and Sharding
MySQL 5.7 Fabric: Introduction to High Availability and Sharding
 
DIY: A distributed database cluster, or: MySQL Cluster
DIY: A distributed database cluster, or: MySQL ClusterDIY: A distributed database cluster, or: MySQL Cluster
DIY: A distributed database cluster, or: MySQL Cluster
 
NoSQL in MySQL
NoSQL in MySQLNoSQL in MySQL
NoSQL in MySQL
 
Vote NO for MySQL
Vote NO for MySQLVote NO for MySQL
Vote NO for MySQL
 
PHP mysqlnd connection multiplexing plugin
PHP mysqlnd connection multiplexing pluginPHP mysqlnd connection multiplexing plugin
PHP mysqlnd connection multiplexing plugin
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLHTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
 
MySQL? Load? Clustering! Balancing! PECL/mysqlnd_ms 1.4
MySQL? Load? Clustering! Balancing! PECL/mysqlnd_ms 1.4MySQL? Load? Clustering! Balancing! PECL/mysqlnd_ms 1.4
MySQL? Load? Clustering! Balancing! PECL/mysqlnd_ms 1.4
 
MySQL 5.6 Global Transaction IDs - Use case: (session) consistency
MySQL 5.6 Global Transaction IDs - Use case: (session) consistencyMySQL 5.6 Global Transaction IDs - Use case: (session) consistency
MySQL 5.6 Global Transaction IDs - Use case: (session) consistency
 
MySQL 5.6 Global Transaction Identifier - Use case: Failover
MySQL 5.6 Global Transaction Identifier - Use case: FailoverMySQL 5.6 Global Transaction Identifier - Use case: Failover
MySQL 5.6 Global Transaction Identifier - Use case: Failover
 
MySQL native driver for PHP (mysqlnd) - Introduction and overview, Edition 2011
MySQL native driver for PHP (mysqlnd) - Introduction and overview, Edition 2011MySQL native driver for PHP (mysqlnd) - Introduction and overview, Edition 2011
MySQL native driver for PHP (mysqlnd) - Introduction and overview, Edition 2011
 
PHPopstar der PHP Unconference 2011
PHPopstar der PHP Unconference 2011PHPopstar der PHP Unconference 2011
PHPopstar der PHP Unconference 2011
 
The mysqlnd replication and load balancing plugin
The mysqlnd replication and load balancing pluginThe mysqlnd replication and load balancing plugin
The mysqlnd replication and load balancing plugin
 
Award-winning technology: Oxid loves the query cache
Award-winning technology: Oxid loves the query cacheAward-winning technology: Oxid loves the query cache
Award-winning technology: Oxid loves the query cache
 
The power of mysqlnd plugins
The power of mysqlnd pluginsThe power of mysqlnd plugins
The power of mysqlnd plugins
 
Mysqlnd query cache plugin benchmark report
Mysqlnd query cache plugin benchmark reportMysqlnd query cache plugin benchmark report
Mysqlnd query cache plugin benchmark report
 
The PHP mysqlnd plugin talk - plugins an alternative to MySQL Proxy
The PHP mysqlnd plugin talk - plugins an alternative to MySQL ProxyThe PHP mysqlnd plugin talk - plugins an alternative to MySQL Proxy
The PHP mysqlnd plugin talk - plugins an alternative to MySQL Proxy
 
Mysqlnd Async Ipc2008
Mysqlnd Async Ipc2008Mysqlnd Async Ipc2008
Mysqlnd Async Ipc2008
 

Último

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Último (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 

MySQL native driver for PHP: Customizing the query cache with user defined storage handlers

  • 1. MySQL native driver for PHP: Customizing the query cache
  • 2. mysqlnd_qc: Customization by user defined storage handler Ulf Wendel, Andrey Hristov MySQL Connectors Team Sun Microsystems
  • 3.
  • 4.
  • 5.
  • 7.
  • 8.
  • 9.
  • 10. Template Method pattern, kind of Core: invariant part of the caching, handler: variant part <?php /* Any PHP MySQL application */ ?> ext/*mysql* ext/*mysql* mysqlnd mysqlnd Query Cache Plugin (mysqlnd_qc core) Storage handler (mysqlnd_qc)
  • 11. Variant and invariant parts (Miss/Put) mysqlnd Cache Plugin handler Cache Plugin core query() Should cache? Is cached? Activate data recorder Call original query() Deactivate recorder Cache wire data is_select() Want to cache statement? find() Available? TTL? Slam defense? Statistics? add() Run time? Data size? Replacement strategy?
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 20.
  • 29. Handler API – Cache Put (I) Application Cache Plugin handler Cache Plugin core *query() Should cache? Yes! Cache entry 'key'? is_select(...) a) Don't cache - return: false b) Cache it – return: int TTL get_hash_key(...) Return key of cache entry. find_in_cache(...) Returns NULL because not found. Do we have 'key'?
  • 30. Handler API – Cache Put (II) Application Cache Plugin handler Cache Plugin core *query() add_to_cache(...) Add to cache if not exists. Return true if added, false if already in cache. Activate data recorder Call original query() Deactivate recorder Cache wire data *store _result() (often implicit)
  • 31. Handler API – Cache Hit (I) Application Cache Plugin handler Cache Plugin core *query() Should cache? Yes! Cache entry 'key'? is_select(...) a) Don't cache - return: false b) Cache it – return: int TTL get_hash_key(...) Return key of cache entry. find_in_cache(...) Search cache entry, check if still valid, return cache entry. Do we have 'key'?
  • 32. Handler API – Cache Hit (II) Application Cache Plugin handler Cache Plugin core *store _result() (often implicit) Client served! Record timings! return_to_cache(...) Cache entry no longer in use by core. (Default needs this) update_stats(...) Run and store time recorded and reported by the core, useful for per-entry stats.
  • 33. Handler API – Cache Miss (I) Application Cache Plugin handler Cache Plugin core *query() Should cache? No! is_select(...) a) Don't cache – return: false b) Cache - see Cache Put (I)
  • 34.
  • 35. string $port – MySQL Server port
  • 36. string $user – MySQL user
  • 37. string $db – MySQL data base
  • 38.
  • 39.
  • 40. string $port – MySQL Server port
  • 41. string $user – MySQL user
  • 42. string $db – MySQL data base
  • 43. string $query – SQL statement
  • 44.
  • 45.
  • 46. This is an ideal place to check not only if a cache entry is available but also to implement tife-to-life (TTL) checks or slam defense logic.
  • 47. For example, if you can find the cache entry but it has expired, you should return NULL to trigger a cache miss.
  • 48.
  • 49.
  • 50. Hardly any pratical meaning to userland handler.
  • 51. Relevant for C based handler that work with references, such as the default handler does. See also mysqlnd_qc.std_data_copy for default handler configuration details.
  • 52.
  • 53. string $data – Binary wire data to cache
  • 54. int $ttl – TTL of the cache entry (s)
  • 55. int $run_t – Run time of uncached query (ms)
  • 56.
  • 57.
  • 58. Timings can be used to build per-entry performance figures such as run time comparisons of the cached and uncached query
  • 59. If the user storage handler makes use of a cache medium that persists over multiple web requests it can happen that two web requests add the same key to the cache almost simultanously – one will be faster. To get the core statistics for cache hits and cache misses right, you can return true or false. See also statistics presentation!
  • 60.
  • 61. Note that you may have to parse the SQL to catch SQL hints that specify the TTL
  • 62. Note the core logic TTL(0) != endless
  • 63.
  • 64.
  • 65. double $run_t – Run time of the cached query
  • 66.
  • 67. Can be used to maintain per-entry cache statistics.
  • 68.
  • 69. Flush all cache entries. Called by the core if the user calls mysqlnd_qc_clear_cache().
  • 70.
  • 71. Returns an array of cache statistics and arbitrary other data which will become part of return value of mysqlnd_qc_get_cache_info().
  • 72. mysqlnd_qc_get_cache_info() returns a hash. The return value of get_stats() will be added to the hash using the key “data”. It is recommended to align the return value of get_stats() with the “data” hash provided by the build-in handlers, in particular Default and APC.
  • 73. Procedural user storage handler void mysqlnd_qc_set_user_handlers( string get_hash_key, string find_query_in_cache, string return_to_cache, string add_query_to_cache_if_not_exists, string query_is_select, string update_cache_stats, string get_stats, string clear_cache ) There is also an OO API to please you – see below. The OO API has additional function callbacks! The OO API is likely to become the future standard. mysqlnd_qc_set_user_handlers()
  • 74. Registering OO user storage handler bool mysqlnd_qc_change_handler (mysqlnd_qc_default_handler handler) bool mysqlnd_qc_change_handler(string handler) Changes the storage handler. Returns false if the current handler cannot be shutdown or the requested handler cannot be initialized. Failing to change the handler should be considered as a fatal error unless the change fails because the requested handler is unknown. You can either change the storage handler to one of build-in handlers or register a user-defined storage handler object derived from mysqlnd_qc_handler_default.
  • 75. Handler API – Handler registration (I) Active handler App / QC Core mysqlnd_qc_change_handler() shutdown active handler: OK! shutdown() return true New handler init() return true init new handler: OK! install to new handler return true
  • 76. Handler API – Handler registration (II) Active handler App / QC Core mysqlnd_qc_change_handler() shutdown active handler: OK! shutdown() return false New handler init() return true init new handler: OK! install to new handler Warning: Shutdown of previous handler '%s' failed return true
  • 77. Handler API – Handler registration(III) Active handler App / QC Core mysqlnd_qc_change_handler() shutdown active handler: OK! shutdown() return false New handler init() return false Warning: Error during changing handler. Init of '%s' failed use build-in “nop” handler Warning: Shutdown of previous handler '%s' failed cache disabled: return false
  • 78.
  • 79. Returns true if the handler is ready to be used. Called upon handler registration triggered by a call to mysqlnd_qc_change_handler().
  • 80. Not available with mysqlnd_set_user_handlers()!
  • 81. Part of the class mysqlnd_qc_handler_default
  • 82. Part of the interface mysqlnd_qc_handler
  • 83.
  • 84. Returns true if the handler has succeeded to clean up resources and is ready to be shutdown. Called upon handler registration triggered by a call to mysqlnd_qc_change_handler().
  • 85. Not available with mysqlnd_set_user_handlers()!
  • 86. Part of the class mysqlnd_qc_handler_default
  • 87. Part of the interface mysqlnd_qc_handler
  • 88.
  • 89.
  • 90.
  • 92.
  • 93.
  • 94. Easy: no need to know all API calls
  • 95.
  • 96. Class mysqlnd_qc_handler_default class mysqlnd_qc_handler_default { public function init() {} public function is_select(...) {} public function get_hash_key(...) {} public function return_to_cache(...) {} public function add_to_cache(...) {} public function find_in_cache(...) {} public function update_cache_stats(...) {} public function get_stats(...) {} public function clear_cache() {} public function shutdown() {} }
  • 97. Quick start: search cache candidates Which queries does the app run? Which ones to cache? class qc_monitor extends mysqlnd_qc_handler_default { public function is_select($query) { printf(&quot;qc_monitor: '%s'&quot;, $query); return parent::is_select($query); } } $monitor = new qc_monitor(); mysqlnd_qc_change_handler($monitor); $mysqli = new mysqli(&quot;host&quot;, &quot;user&quot;, &quot;passwd&quot;, &quot;db&quot;); $mysqli->query(&quot;SELECT 1&quot;);
  • 98. Quick start: query monitoring (I) class qc_monitor extends mysqlnd_qc_handler_default { private $key_to_query = array(); public function get_hash_key($h, $p, $u, $d, $q, $p) { $key = parent::get_hash_key($h, $p, $u, $d, $q, $p); $this->key_to_query[$key] = $query; return $key; } public function is_select($query) { return true; } /* continued */
  • 99. Quick start: query monitoring (II) /* continued */ public function add_to_cache ($key, $data, $ttl, $run_t, $store_t, $row_c) { printf(&quot;Query = '%s'&quot;, $this->key_to_query[$key]); printf(&quot; run time = %d ms&quot;, $run_t); printf(&quot; store time = %d ms&quot;, $store_t); printf(&quot; size = %d rows&quot;, $row_c); /* do not add to cache! */ return false; } }
  • 100.
  • 101. MySQL server has gone away
  • 102.
  • 104. Develop everything from ground up interface mysqlnd_qc_handler { public function is_select(...) {} public function get_hash_key(...) {} public function return_to_cache(...) {} public function add_to_cache(...) {} public function find_in_cache(...) {} public function update_cache_stats(...) {} public function get_stats(...) {} public function clear_cache() {} } No limits – basic usage pattern like before
  • 105. Cache Miss Client 2...100 Client 2...100 Client 2...100 Master class: Slam defense Serve stale data to avoid MySQL overloading Client 1 Client 2...n MySQL Client 2...100 Client 2...100 Client 2...100 Client 1 Client 2...n Slam Stale Hit MySQL Cache Hit
  • 106.
  • 107.
  • 108. $this->cache is not shared among PHP instances
  • 110. Master class: slam defense (I) class qc_monitor extends mysqlnd_qc_handler_default { private $cache = array(); public function add_to_cache( $key, $data, $ttl, $run_t, $store_t, $row_c) { printf(&quot;add : put(ttl = %d)&quot;, $ttl); $this->cache[$key] = array( &quot;data&quot; => $data, &quot;valid_until&quot; => microtime(true) + $ttl, &quot;slam_until&quot; => NULL ); return true; } /* continued */
  • 111. Master class: slam defense (II) public function find_in_cache($key) { if (!isset($this->cache[$key])) { printf(&quot;find: miss&quot;); return NULL; } $now = microtime(true); if ($this->cache[$key][&quot;valid_until&quot;] > $now) { printf(&quot;find: hit&quot;); return $this->cache[$key][&quot;data&quot;]; } /* continued */
  • 112. Master class: slam defense (III) if ($this->cache[$key][&quot;slam_until&quot;]) { if ($this->cache[$key][&quot;slam_until&quot;] > $now) { printf(&quot;find: hit, slam defense active&quot;); return $this->cache[$key][&quot;data&quot;]; } else { printf(&quot;find: miss, slam defense expired&quot;); unset($this->cache[$key]); return NULL; } } printf(&quot;find: expired, slam defense starts&quot;); $this->cache[$key][&quot;slam_until&quot;] = $now + 2; return $this->cache[$key][&quot;data&quot;]; } }
  • 113.
  • 114. Query cache plugin benchmark impressions
  • 115. Dig deeper with QC statistics
  • 116. Developing user storage handler Further reading
  • 117. The End Feedback: ulf.wendel@sun.com The End Feedback: [email_address] , [email_address]