MySQL advanced knowledge and Optimization (V): application optimization, query cache optimized memory management and optimization, concurrency parameter optimization

Application Optimization

1 using connection pooling

For access to the database, the establishment of the cost of connection is relatively expensive, because we frequently create close the connection, it is more resource-intensive, we need to establish a database connection pool to improve performance access.

2 reduce access for MySQL

2.1 to avoid repeated data retrieval

When writing application code, you need to be able to sort out the logical access to the database. Can be a result of the connection is obtained, it does not connect the two, which can reduce the repetitive requests for database useless.

For example, id and name fields need to acquire books, the query is as follows:

 select id , name from tb_book;

After that, there is a need to obtain information in the book business logic state, the query is as follows:

select id , status from tb_book;

In this way, you need to submit two requests to the database, the database will need to do two queries. In fact, you can get the desired results with a SQL statement.

select id, name , status from tb_book;
2.2 increase cache layer

In the application, we can increase the cache in the application layer to achieve the purpose of alleviating database load. Buffer layer there are many, there are many ways to achieve, can be achieved as long as the burden of reducing the database can meet the application requirements can be.

Can be part of the data extracted from the database into the text stored in the application side, or by using a frame (Mybatis, Hibernate) provides a buffer / cache, used redis database or cache data.

3 Load Balancing

Load balancing is a very common application used in an optimization method, its mechanism is to use some kind of balancing algorithm, a fixed amount of load to be distributed on different servers, in order to reduce the load on a single server to achieve optimal results .

3.1 query using the MySQL replication shunt

MySQL from the master by replication for separate read and write the master node CRUD operations away, away from the query node, thereby reducing the pressure reading and writing a single server.

Here Insert Picture Description

3.2 uses a distributed database architecture

Distributed database architecture for large amounts of data, high load conditions, it has good scalability and high availability. By distributing data across multiple servers, you can achieve load balancing across multiple servers to improve access efficiency.

Mysql query cache optimization

1 Overview

Open Mysql query cache, when performing the exact same SQL statement, the server will read directly from the cache As a result, when the data is modified before the cache will fail more frequently modified table is not suitable for query cache.

2 operation flow

Here Insert Picture Description

  1. 客户端发送一条查询给服务器;
  2. 服务器先会检查查询缓存,如果命中了缓存,则立即返回存储在缓存中的结果。否则进入下一阶段;
  3. 服务器端进行SQL解析、预处理,再由优化器生成对应的执行计划;
  4. MySQL根据优化器生成的执行计划,调用存储引擎的API来执行查询;
  5. 将结果返回给客户端。

3 查询缓存配置

  1. 查看当前的MySQL数据库是否支持查询缓存:

    SHOW VARIABLES LIKE 'have_query_cache';	
    

    Here Insert Picture Description

  2. 查看当前MySQL是否开启了查询缓存 :

    SHOW VARIABLES LIKE 'query_cache_type';
    

    Here Insert Picture Description

  3. 查看查询缓存的占用大小 :

    SHOW VARIABLES LIKE 'query_cache_size';
    

    Here Insert Picture Description

  4. 查看查询缓存的状态变量:

    SHOW STATUS LIKE 'Qcache%';
    

    Here Insert Picture Description

    各个变量的含义如下:

    参数 含义
    Qcache_free_blocks 查询缓存中的可用内存块数
    Qcache_free_memory 查询缓存的可用内存量
    Qcache_hits 查询缓存命中数
    Qcache_inserts 添加到查询缓存的查询数
    Qcache_lowmen_prunes 由于内存不足而从查询缓存中删除的查询数
    Qcache_not_cached 非缓存查询的数量(由于 query_cache_type 设置而无法缓存或未缓存)
    Qcache_queries_in_cache 查询缓存中注册的查询数
    Qcache_total_blocks 查询缓存中的块总数

4 开启查询缓存

MySQL的查询缓存默认是关闭的,需要手动配置参数 query_cache_type , 来开启查询缓存。query_cache_type 该参数的可取值有三个 :

含义
OFF 或 0 查询缓存功能关闭
ON 或 1 查询缓存功能打开,SELECT的结果符合缓存条件即会缓存,否则,不予缓存,显式指定 SQL_NO_CACHE,不予缓存
DEMAND 或 2 查询缓存功能按需进行,显式指定 SQL_CACHE 的SELECT语句才会缓存;其它均不予缓存

在 /usr/my.cnf 配置中,增加以下配置 :

Here Insert Picture Description

配置完毕之后,重启服务既可生效 ;

然后就可以在命令行执行SQL语句进行验证 ,执行一条比较耗时的SQL语句,然后再多执行几次,查看后面几次的执行时间;获取通过查看查询缓存的缓存命中数,来判定是否走查询缓存。

5 查询缓存SELECT选项

可以在SELECT语句中指定两个与查询缓存相关的选项 :

SQL_CACHE : 如果查询结果是可缓存的,并且 query_cache_type 系统变量的值为ON或 DEMAND ,则缓存查询结果 。

SQL_NO_CACHE : 服务器不使用查询缓存。它既不检查查询缓存,也不检查结果是否已缓存,也不缓存查询结果。

例子:

SELECT SQL_CACHE id, name FROM customer;
SELECT SQL_NO_CACHE id, name FROM customer;

6 查询缓存失效的情况

1) SQL 语句不一致的情况, 要想命中查询缓存,查询的SQL语句必须一致。

SQL1 : select count(*) from tb_item;
SQL2 : Select count(*) from tb_item;

2) 当查询语句中有一些不确定的时,则不会缓存。如 : now() , current_date() , curdate() , curtime() , rand() , uuid() , user() , database() 。

SQL1 : select * from tb_item where updatetime < now() limit 1;
SQL2 : select user();
SQL3 : select database();

3) 不使用任何表查询语句。

select 'A';

4) 查询 mysql, information_schema或 performance_schema 数据库中的表时,不会走查询缓存。

select * from information_schema.engines;

5) 在存储的函数,触发器或事件的主体内执行的查询。

6) 如果表更改,则使用该表的所有高速缓存查询都将变为无效并从高速缓存中删除。这包括使用MERGE映射到已更改表的表的查询。一个表可以被许多类型的语句,如被改变 INSERT, UPDATE, DELETE, TRUNCATE TABLE, ALTER TABLE, DROP TABLE,或 DROP DATABASE 。

Mysql内存管理及优化

1 内存优化原则

1) 将尽量多的内存分配给MySQL做缓存,但要给操作系统和其他程序预留足够内存。

2) MyISAM 存储引擎的数据文件读取依赖于操作系统自身的IO缓存,因此,如果有MyISAM表,就要预留更多的内存给操作系统做IO缓存。

3) 排序区、连接区等缓存是分配给每个数据库会话(session)专用的,其默认值的设置要根据最大连接数合理分配,如果设置太大,不但浪费资源,而且在并发连接较高时会导致物理内存耗尽。

2 MyISAM 内存优化

myisam存储引擎使用 key_buffer 缓存索引块,加速myisam索引的读写速度。对于myisam表的数据块,mysql没有特别的缓存机制,完全依赖于操作系统的IO缓存。

key_buffer_size

key_buffer_size决定MyISAM索引块缓存区的大小,直接影响到MyISAM表的存取效率。可以在MySQL参数文件中设置key_buffer_size的值,对于一般MyISAM数据库,建议至少将1/4可用内存分配给key_buffer_size。

在/usr/my.cnf 中做如下配置:

key_buffer_size=512M

read_buffer_size

如果需要经常顺序扫描myisam表,可以通过增大read_buffer_size的值来改善性能。但需要注意的是read_buffer_size是每个session独占的,如果默认值设置太大,就会造成内存浪费。

read_rnd_buffer_size

对于需要做排序的myisam表的查询,如带有order by子句的sql,适当增加 read_rnd_buffer_size 的值,可以改善此类的sql性能。但需要注意的是 read_rnd_buffer_size 是每个session独占的,如果默认值设置太大,就会造成内存浪费。

3 InnoDB 内存优化

innodb用一块内存区做IO缓存池,该缓存池不仅用来缓存innodb的索引块,而且也用来缓存innodb的数据块。

innodb_buffer_pool_size

该变量决定了 innodb 存储引擎表数据和索引数据的最大缓存区大小。在保证操作系统及其他程序有足够内存可用的情况下,innodb_buffer_pool_size 的值越大,缓存命中率越高,访问InnoDB表需要的磁盘I/O 就越少,性能也就越高。

innodb_buffer_pool_size=512M

innodb_log_buffer_size

决定了innodb重做日志缓存的大小,对于可能产生大量更新记录的大事务,增加innodb_log_buffer_size的大小,可以避免innodb在事务提交前就执行不必要的日志写入磁盘操作。

innodb_log_buffer_size=10M

Mysql并发参数调整

从实现上来说,MySQL Server 是多线程结构,包括后台线程和客户服务线程。多线程可以有效利用服务器资源,提高数据库的并发性能。在Mysql中,控制并发连接和线程的主要参数包括 max_connections、back_log、thread_cache_size、table_open_cahce。

1 max_connections

采用max_connections 控制允许连接到MySQL数据库的最大数量,默认值是 151。如果状态变量 connection_errors_max_connections 不为零,并且一直增长,则说明不断有连接请求因数据库连接数已达到允许最大值而失败,这是可以考虑增大max_connections 的值。

Mysql 最大可支持的连接数,取决于很多因素,包括给定操作系统平台的线程库的质量、内存大小、每个连接的负荷、CPU的处理速度,期望的响应时间等。在Linux 平台下,性能好的服务器,支持 500-1000 个连接不是难事,需要根据服务器性能进行评估设定。

2 back_log

back_log 参数控制MySQL监听TCP端口时设置的积压请求栈大小。如果MySql的连接数达到max_connections时,新来的请求将会被存在堆栈中,以等待某一连接释放资源,该堆栈的数量即back_log,如果等待连接的数量超过back_log,将不被授予连接资源,将会报错。5.6.6 版本之前默认值为 50 , 之后的版本默认为 50 + (max_connections / 5), 但最大不超过900。

如果需要数据库在较短的时间内处理大量连接请求, 可以考虑适当增大back_log 的值。

3 table_open_cache

This parameter is used to control all SQL statements execution threads openable table cache number, and when the execution of SQL statements, an SQL execution thread for each open to at least one table cache. The value of this parameter should be set to the maximum number of connections max_connections and the maximum number associated with each connection table involved in the query execution of the set:

​ max_connections x N ;

4 thread_cache_size

In order to speed up the connection to the database, MySQL will cache a certain amount of customer service threads for reuse, can control the number of MySQL thread cache of customer service via the parameter thread_cache_size.

5 innodb_lock_wait_timeout

This parameter is used to set InnoDB row lock wait time of the transaction, the default value is 50ms, you can be dynamically set according to need. The need for rapid business feedback system, the wait time can be adjusted in small row locks to avoid transaction pending for a long time; for batch processing program running in the background, the wait time can be a row lock up high to avoid large rollback operation occurs.

Published 109 original articles · won praise 47 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_43934607/article/details/103689294