Home Backend Development PHP Tutorial 一个有关MYSQL的文章.E文的.MySQLs Query Cache_PHP教程

一个有关MYSQL的文章.E文的.MySQLs Query Cache_PHP教程

Jul 13, 2016 pm 05:27 PM
cache http mysql query article of


http://www.discuz.net/viewthread.php?tid=43137&sid=G4jizDNovember 18, 2003MySQLs Query CacheBy Ian GilfillanA typical scenarioBoss: Our new website is crawling! How can it be, we have four state-of-the-art web servers - whats the problem?You: Well, the web servers are fine - its the database server thats struggling.Boss: What? You told me this MySQL thing was fast, that we didnt need Oracle, and now you say it cant cope! How can this be?You: Well, the web servers are behaving so well that theyre pushing through lots of queries, and the database cant manage to process all of them at the same time. Its only one database, and lots of web servers...Boss: Its too late to buy Oracle now - what are we going to do!?Big Boss to Boss(in the bosss mind): This project has been a disaster from the beginning - now you want me to delay it while we install a new database, and spend a whole lot more! Do you think were made of money!? Im calling in someone who knows what theyre doing - youre history buddy.Colleague (about to take your job): Wait, I think I can solve the problem!So, what does your colleague know that you dont? How can he save the day and let the boss get all the credit? Our scenario is too imprecise to generalize, and there are many possible solutions. You can read about optimizing queries and indexes, optimizing by improving the hardware, and tweaking the MySQL variables, using the slow query log, and of course, there are other methods such as replication. However, MySQL 4 provides one feature that can prove very handy - a query cache. In a situation where the database has to repeatedly run the same queries on the same data set, returning the same results each time, MySQL can cache the result set, avoiding the overhead of running through the data over and over. Usually, you would want to implement some sort of caching on the web server, but there are times when this is not possible, and then it is the query cache you will look to for help.Setting up the query cacheTo make sure MySQL uses the query cache, there are a few variables you need to set in the configuration file (usually my.cnf or my.ini). First, is the query_cache_type. There are three possible settings: 0 (for off, do not use), 1 (for on, cache queries) and 2 (on demand, discussed more below). To ensure it is always on, place: query-cache-type = 1in the configuration file. If you started the server having only made this change, you would see the following cache variables set: mysql> SHOW VARIABLES LIKE %query_cache%;+-------------------+---------+| Variable_name | Value |+-------------------+---------+| have_query_cache | YES || query_cache_limit | 1048576 || query_cache_size | 0 || query_cache_type | ON |+-------------------+---------+4 rows in set (0.06 sec)Note that these are results from MySQL 4.0.x - youll see more in versions 4.1.x and beyond. The query_cache_type will be set to ON or OFF as appropriate. However, there is one more to set, and that is the query_cache_size. If set to 0 (the default), the cache will be disabled. This variable determines the memory, in bytes, used for the query cache. For our purposes, we will set it to 20 MB: query-cache-size = 20MThe amount is shown in bytes: mysql> SHOW VARIABLES LIKE %query_cache%;+-------------------+----------+| Variable_name | Value |+-------------------+----------+| have_query_cache | YES || query_cache_limit | 1048576 || query_cache_size | 20971520 || query_cache_type | ON |+-------------------+----------+4 rows in set (0.06 sec)The Query cache in action (almost)For this tutorial, I used a dump from Wikipedia, the open content encyclopedia (you can find the dumps here. I am using a fairly slow machine, with nothing else happening on it, to minimize interference in the results. Lets run the same query twice, and see how much improvement we see the second time: SELECT * FROM cur;...14144 rows in set (2.96 sec)Now we run the same query again: SELECT * FROM cur; 14144 rows in set (3.02 sec) Now we run the same query again: SELECT * FROM cur; 14144 rows in set (3.02 sec) What is happening? We would expect the second query to take noticeably less time. Lets examine some of the status variables to get a better picture. mysql> SHOW STATUS LIKE %qcache%;+-------------------------+----------+| Variable_name | Value |+-------------------------+----------+| Qcache_queries_in_cache | 0 || Qcache_inserts | 2 || Qcache_hits | 0 || Qcache_lowmem_prunes | 0 || Qcache_not_cached | 2 || Qcache_free_memory | 20962720 || Qcache_free_blocks | 1 || Qcache_total_blocks | 1 |+-------------------------+----------+8 rows in set (0.00 sec)The two queries we ran are both recorded (by Qcache_inserts), but neither of them have been cached. (You may get different results if other queries have been running.) The problem is that the result set is too big. I used the Wikipedia Esperanto dump (4MB compressed - the English dump is 135MB, and even though my English is better than my Esperanto, bandwidth is expensive in South Africa!), but it is immaterial, as even that is more than the query cache can handle by default. There are two limits in play here - the limit for each individual query is determined by the value of query_cache_limit, which is 1MB by default. Moreover, the limit of the cache in total is determined by query_cache_size, which we have seen already. The former limit applies here. If a result set is greater than 1M, it is not cached. The Query cache in action (really)Lets try a smaller query: SELECT cur_is_new FROM cur WHERE cur_user_text > Y...2336 rows in set (0.38 sec)Lets see if this one was cached:mysql> SHOW STATUS LIKE %qcache%;+-------------------------+----------+| Variable_name | Value |+-------------------------+----------+| Qcache_queries_in_cache | 1 || Qcache_inserts | 3 || Qcache_hits | 0 || Qcache_lowmem_prunes | 0 || Qcache_not_cached | 2 || Qcache_free_memory | 20947592 || Qcache_free_blocks | 1 || Qcache_total_blocks | 4 |+-------------------------+----------+8 rows in set (0.00 sec)There is now a query in the cache. If it took 0.38 seconds to run the first time, lets see if we notice an improvement the second time: SELECT cur_is_new FROM cur WHERE cur_user_text > Y...2336 rows in set (0.11 sec)Much better! And, looking at the status again: mysql> SHOW STATUS LIKE %qcache%;+-------------------------+----------+| Variable_name | Value |+-------------------------+----------+| Qcache_queries_in_cache | 1 || Qcache_inserts | 3 || Qcache_hits | 1 || Qcache_lowmem_prunes | 0 || Qcache_not_cached | 2 || Qcache_free_memory | 20947592 || Qcache_free_blocks | 1 || Qcache_total_blocks | 4 |+-------------------------+----------+8 rows in set (0.06 sec)The cache has been hit once. The status variables above should be fairly self-explanatory. Available memory for the cache has gone from 20962720 to 20947592 bytes. The most useful variable for future tuning is Qcache_lowmem_prunes. Each time a cached query is removed from the query cache, (because MySQL needs to make space for another), this value will be incremented. If it increases quickly, and you still have memory to spare, you can up the query_cache_size, while if it never increases, you can reduce the cache size. Lets run the query again, with a slight difference, as follows: SELECT cur_is_new from cur where cur_user_text > Y...2336 rows in set (0.33 sec)That took longer than we would have expected. Lets look at the status variables to see whats up: mysql> SHOW STATUS LIKE %qcache%;+-------------------------+----------+| Variable_name | Value |+-------------------------+----------+| Qcache_queries_in_cache | 2 || Qcache_inserts | 4 || Qcache_hits | 1 || Qcache_lowmem_prunes | 0 || Qcache_not_cached | 2 || Qcache_free_memory | 20932976 || Qcache_free_blocks | 1 || Qcache_total_blocks | 6 |+-------------------------+----------+The query has not made use of the cache - in fact, MySQL has inserted another query in the cache! The proble

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/531868.htmlTechArticlehttp://www.discuz.net/viewthread.php?tid=43137+-------------------+---------+| Variable_name | Value |+-------------------+---------+| have_query_cache | YES || query_cache_limit |...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

mysql whether to change table lock table mysql whether to change table lock table Apr 08, 2025 pm 05:06 PM

When MySQL modifys table structure, metadata locks are usually used, which may cause the table to be locked. To reduce the impact of locks, the following measures can be taken: 1. Keep tables available with online DDL; 2. Perform complex modifications in batches; 3. Operate during small or off-peak periods; 4. Use PT-OSC tools to achieve finer control.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

Can mysql run on android Can mysql run on android Apr 08, 2025 pm 05:03 PM

MySQL cannot run directly on Android, but it can be implemented indirectly by using the following methods: using the lightweight database SQLite, which is built on the Android system, does not require a separate server, and has a small resource usage, which is very suitable for mobile device applications. Remotely connect to the MySQL server and connect to the MySQL database on the remote server through the network for data reading and writing, but there are disadvantages such as strong network dependencies, security issues and server costs.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

See all articles