Home Database Mysql Tutorial Detailed explanation of cache optimization for MySQL optimization (1)

Detailed explanation of cache optimization for MySQL optimization (1)

Mar 16, 2017 pm 02:21 PM

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
Copy after login

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  |
+-----------------------------+----------+
Copy after login

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  |
+--------------------------+-------+
Copy after login

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


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

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 |
+-------------------+-------+
Copy after login

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

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 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

Video Face Swap

Video Face Swap

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

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)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

See all articles