search
HomeDatabaseMysql TutorialDetailed explanation of cache optimization for MySQL optimization (1)

The most frequently asked question is about MySQL databasePerformance optimization, so I plan to write a MySQL databaseperformance optimization recently This series of articles hopes to be helpful to junior and intermediate MySQL DBAs and other friends who are interested in MySQL performance optimization.

I am happy that a blogger marked my article. After I know Mark, I rarely come back and continue to pay attention. But it shows from the side that when the blogger clicks on the blog, he feels that this blog is valuable and can make up for his lack of knowledge. The most important thing about a blog is that it is useful to yourself. If it is useful to others, that is the best result. The purpose of my insistence on blogging is so that when I forget a knowledge point, I can find a reliable solution as quickly as possible. When you remember your summarized knowledge, you will forget it more slowly. After a long time, this part of the knowledge finally turns into your own words, then you are no longer afraid of forgetting. This blog will continue to talk about the content of MySQL. This article talks about caching optimization. The process of talking about it is also my learning process.

Let’s take a look at our mysql version first. The version installed on my mac is 5.7, and many contents have changed. What we are talking about here is mainly version 5.6.


[root@roverliang ~]# mysql --version
mysql Ver 14.14 Distrib 5.6.24, for Linux (x86_64) using EditLine wrapper

1. MySQL cache classification

The optimization of MySQL refers to a large system. During the interview, I It is said from the aspect of SQL statement optimization. This kind of optimization also has an effect, but it is optimized from the logical aspect. But when all the logical levels can no longer be optimized, all indexes have been added, and the table structure is reasonably designed, but when encountering high concurrency, why can't MySQL still handle it? Of course, the pressure on MySQL can be alleviated through other aspects, which we will not discuss here for now. For MySQL, we must try our best to squeeze the performance of the machine so that all computing resources can serve us without wasting them. MySQL runs on a server, specifically a Linux server. Then the server's hard disk, CPU, memory, and network all affect the performance of MySQL. MySQL consumes a lot of memory. The MySQL memory of the online server consumes about 80%. If the memory is too small, there is actually very little room for other optimizations.

In addition, connection is also an important aspect that affects MySQL performance. The connection between the MySQL client and the MySQL server is the result of repeated handshakes between the MySQL client and the MySQL server. Each 'handshake' goes through identity verification, permission verification, etc. The handshake requires certain network resources and MySQL server memory resources.

I have to mention lock competition. For databases with relatively high concurrency performance requirements, if there is fierce lock competition, the performance of the database will be a big blow. Lock contention will significantly increase the overhead of thread context switching, which is independent of the expected demand.

2. show status and show variables

In the first few blogs of the MySQL series, you will often see these commands, so let’s take a look at these two commands separately. What information does this command display to the MySQL system administrator:

show status

When the MySQL service is running, the status of the MySQL service instance Information is dynamic. Use this command to display the session status variable information of the current MySQL server connection. By default variable names have the first letter capitalized.

show variables

show variables is used to display various system variables of the MySQL service instance (such as: global system variables, session system variables, staticvariables), these variables contain the default values ​​of MySQL compile-time parameters, or the parameter values ​​set in my.cnf. System variables or parameters are a static concept. By default, system variable names are all lowercase letters.

Use the MySQL command show status or show session status to view the session variable information of the current MySQL server connection. The variable value of the session status is related to the current MySQL client. Valid, for example: Opened_tables, Opened_table_definitions status variables.

Caching mechanism

缓存之所以有效,主要是因为程序运行时对内存或者外存的访问呈现局部性特征,局部性特征为空间局部性和时间局部性两方面。时间局部性是指刚刚访问过的数据近期可能再次被访问,空间局部性是指,某个位置被访问后,其相邻的位置的数据很可能被访问到。而MySQL的缓存机制就是把刚刚访问的数据(时间局部性)以及未来即将访问到的数据(空间局部性)保存到缓存中,甚至是高速缓存中。从而提高I/O效率。

按照缓存读写功能的不同,MySQL将缓存分为Buffer缓存和Cache缓存。

Buffer缓存。由于硬盘的写入速度过慢,或者频繁的I/O,对于硬盘来说是极大的效率浪费。那么可以等到缓存中储存一定量的数据之后,一次性的写入到硬盘中。Buffer 缓存主要用于写数据,提升I/O性能。

Cache 缓存。 Cache 缓存一般是一些访问频繁但是变更较少的数据,如果Cache缓存已经存储满,则启用LRU算法,进行数据淘汰。淘汰掉最远未使用的数据,从而开辟新的存储空间。不过对于特大型的网站,依靠这种策略很难缓解高频率的读请求,一般会把访问非常频繁的数据静态化,直接由nginx返还给用户。程序和数据库I/O设备交互的越少,则效率越高。

三、MySQL 超时

在使用MySQL的过程中,可能会出现各种超时(timeout)异常,典型的有连接超时、锁等待等。

查看超时时间的类型有哪些:


mysql> show variables like '%timeout%';
+-----------------------------+----------+
| Variable_name        | Value  |
+-----------------------------+----------+
| connect_timeout       | 10    |
| delayed_insert_timeout   | 300   |
| innodb_flush_log_at_timeout | 1    |
| innodb_lock_wait_timeout  | 50    |
| innodb_rollback_on_timeout | OFF   |
| interactive_timeout     | 28800  |
| lock_wait_timeout      | 31536000 |
| net_read_timeout      | 30    |
| net_write_timeout      | 60    |
| rpl_stop_slave_timeout   | 31536000 |
| slave_net_timeout      | 3600   |
| wait_timeout        | 28800  |
+-----------------------------+----------+

1、连接超时(connect_timeout)

connect_timeout默认为10s,获取MySQL连接是客户机与服务器之间握手的结果,并且是多次握手的结果,每次握手,除了验证账户名和身份信息外,还需要验证主机、域名解析。如果客户机和服务器之间存在网络故障,可以通过connect_timeout参数来设置,防止它们之间重复握手。

interactive_timeout指的是交互式的终端,在命令行中输入的这种。超过了其设置的默认值就会断开。

wait_timeout指的是非交互式的终端,比如PHP实例化的Mysql连接,一直占用着,超过了这个参数设置的值,就会自动断开。

net_write_timeout MySQL服务器产生一个很大的数据集,MySQL客户机在该值设置的时间内不能接受完毕,则会断开连接。

net_read_timeout MySQL客户机读取了一个很大的数据,在设置值内不能读取完毕,则会自动断开连接。

InnoDB锁等待超时


mysql> show variables like 'innodb_lock_wait_timeout';
+--------------------------+-------+
| Variable_name      | Value |
+--------------------------+-------+
| innodb_lock_wait_timeout | 50  |
+--------------------------+-------+

InnoDB 的锁等待时间默认为50s,设置行级锁锁等待的值,当出现锁等待的时候,等待时长超过该值会导致锁等待的SQL回滚(不是整个事务回滚)。如果希望整个事务回滚,需要开启innodb_rollback_on_timeout参数。


mysql> show variables like '%rollback%';
+----------------------------+-------+
| Variable_name       | Value |
+----------------------------+-------+
| innodb_rollback_on_timeout | OFF  |
| innodb_rollback_segments  | 128  |
+----------------------------+-------+

innodb_rollback_on_timeout设置为true 后,遇到事务超时,会回滚整个事务的操作。

复制连接超时

当主从配置是,从服务器(slave)从主服务器(master)读取二进制日志失败后,从服务器会等待 slave_net_timeout 后,从新从master机拉去二进制日志。可以设置成10s.


mysql> show variables like 'slave_net_timeout';
+-------------------+-------+
| Variable_name   | Value |
+-------------------+-------+
| slave_net_timeout | 3600 |
+-------------------+-------+

这部分总结,应该是周日晚上就该整理好的,结果拖到了今天。后面的计划又要后延了,拖延症真严重。

The above is the detailed content of Detailed explanation of cache optimization for MySQL optimization (1). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)