my.cnf
[client] 对mysql的全部客端都生效的
[mysql] 只对mysql这个命令有效了
[mysqd]
[mysqld_multi] 多实例启动
[mysqld_safe]
[mysqldNNNN]
#[global]
set SQL_SAFE_UPDATES = 1;
运行一段时间,mysql参数优化
1 慢查询
show variables like '%slow%';
mysql> show variables like '%slow%';
+---------------------------+-----------------------------------------+
| Variable_name | Value |
+---------------------------+-----------------------------------------+
| log_slow_admin_statements | ON |
| log_slow_slave_statements | OFF |
| slow_launch_time | 2
| slow_query_log | ON 指定是否开启慢查询日志
| slow_query_log_file | /data/mysqldata/3306/log/mysql-slow.log 指定慢日志文件存放位置,能够为空,系统会给一个缺省的文件host_name-slow.log
log-warnings
log_error_verbosity,The log_error_verbosity system variable is preferred over,and should be used instead of, the --log-warnings
log_queries_not_using_indexes: 不使用索引的慢查询日志是否记录到索引
long_query_time : 设定慢查询的阀值,超出次设定值的SQL即被记录到慢查询日志,缺省值为10s
show global status like '%slow%';
show variables like '%long_query_time%';
> set global log_slow_queries=1;
> set session long_query_time=2;
> set global long_query_time=2;
> show warnings;
> set global log_queries_not_using_indexes=1;
mysql> show global status like '%slow%';
+---------------------+-------+
| Variable_name | Value |
+---------------------+-------+
| Slow_launch_threads | 0 |
| Slow_queries | 3 |
mysql> set global slow_query_log=on;
mysql> show variables like '%error%';php
innodb buffer的预读取是否有用
(system@127.0.0.1:3306) [test]> show global status like 'Innodb_buffer_pool_read%';
| Innodb_buffer_pool_read_ahead | 767 | 预读取的页
| Innodb_buffer_pool_read_ahead_evicted | 0 | 预读取被清除的页
( 1 - Innodb_buffer_pool_read_ahead_evicted / Innodb_buffer_pool_read_ahead ) *100 = xx%
innodb_read_ahead_threshold:此参数是设置预读取的页数,设置0是关闭预读取功能
(system@127.0.0.1:3306) [(none)]> show global variables like 'innodb_read_ahead_threshold';
+-----------------------------+-------+
| Variable_name | Value |
+-----------------------------+-------+
| innodb_read_ahead_threshold | 56 |
+-----------------------------+-------+
(system@127.0.0.1:3306) [test]> show global variables like 'innodb%log%';
Handler_read_rnd
Select_full_join
Select_scan
Connections
Threads_created html
2 链接数
show variables like 'max_connections';
show global status like 'Max_used_connections';
max_used_connections / max_connections * 100% = 99.6% (理想值 ≈ 85%)前端
3 Key_buffer_size mysql进行group by时候,可能会用到myisam的临时表
key_buffer_size = 32M
show variables like 'key_buffer_size';
show global status like 'key_read%';
mysql> show global status like 'key_read%';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Key_read_requests | 18 |--索引读请求
| Key_reads | 2 |--硬盘读mysql
4 临时表
show global status like 'created_tmp%';
(system@127.0.0.1:3306) [test]> show variables like '%tmp%';
mysql> show global status like 'created_tmp%';
+-------------------------+-------+
| Variable_name | Value |
+-------------------------+-------+
| Created_tmp_disk_tables | 25 |--在磁盘上建立临时表
| Created_tmp_files | 5 |--MySQL服务建立的临时文件文件数
| Created_tmp_tables | 24283 |--每次建立临时表
show variables where Variable_name in ('tmp_table_size', 'max_heap_table_size');
max_heap_table_size Default 16M(5.6)
Created_tmp_tables
服务器执行语句时自动建立的内存临时表的数量。若是Created_tmp_disk_tables值较大。须要增长tmp_table_size和max_heap_table_size的值。
内部临时表最初建立为一个内存中的表,但变得太大时,MySQL会自动将其转换为磁盘上的表。在内存中的临时表的最大尺寸是最小的tmp_table_size
和max_heap_table_size的值控制。若是Created_tmp_disk_tables较大,可能要增长tmp_table_size和max_heap_table_size值。以减小在内存临时表被转换为磁盘上的表。
出现临时表的缘由
(1)若是有一个ORDER BY子句和一个不一样的GROUP BY子句,或若是ORDER BY或GROUP BY包含第一个表中的其余列,建立一个临时表
(2)DISTINCT加上ORDER BY可能须要一个临时表
(3)若是使用SQL_SMALL_RESULT选项,MySQL使用内存中的临时表
(4)表中有BLOB或TEXT列的存在
(5)在GROUP BY或DISTINCT子句大于512字节的任意列的存在
(6)在查询中,若是使用UNION或UNION ALL的任何列大于512字节
(7)GROUP BY和ORDER BY 没法使用索引时
tmp_table_size=32M 做用:该参数用于决定内部内存(memory)临时表的最大值,每一个线程都要分配(实际起限制做用的是tmp_table_size和
max_heap_table_size的最小值),若是内存临时表超出了限制,MySQL就会自动地把它转化为基于磁盘的MyISAM表
,优化查询语句的时候,要避免使用临时表,若是实在避免不了的话,要保证这些临时表是存在内存中的。
现象:若是复杂的SQL语句中包含了group by/distinct等不能经过索引进行优化而使用了临时表,则会致使SQL执行时间加长。
建议:若是应用中有不少group by/distinct等语句,同时数据库有足够的内存,能够增大tmp_table_size(max_heap_table_size)的值,以此来提高查询性能。
5 open table状况
show global status like 'open%tables%';
show variables like '%cache%';
6 进程使用状况
show global status like 'Thread%';
show variables like 'thread_cache_size';#150
当有链接被关闭时,mysql检查缓存中是否还有空闲来缓存线程,若有,就缓存该线程以备下次链接重用,没有就销毁
7 查询缓存(query cache)
show global status like 'qcache%';
show variables like 'query_cache%';
> show global status like 'binlog_ca%';
在事务提交之后,binlog是先写入缓存,而后由操做系统决定什么时候刷新到磁盘上。若是事务大小超过定义的缓存,则在磁盘上建立一个临时文件。
Binlog_cache_use
binlog_cache_size=32K =4M
使用临时二进制日志缓存的事务数量,若是有较大的事务,能够增长该值
Binlog_cache_disk_use
使用临时二进制日志缓存可是超过binlog_cache_size的值并使用临时文件来保存事务中的语句的事务数量。若是该值很大,须要加大binlog_cache_size的值
8 排序使用状况
show global status like 'sort%';
mysql> show global status like 'sort%';
+-------------------+--------+
| Variable_name | Value |
+-------------------+--------+
| Sort_merge_passes | 0 |
| Sort_range | 666 |
| Sort_rows | 420043 |
| Sort_scan | 22526 |
Sort_merge_passes 包括两步。MySQL 首先会尝试在内存中作排序使用的内存大小由系统变量Sort_buffer_size 决定,
若是它的大小不够把全部的记录都读到内存中MySQL 就会把每次在内存中排序的结果存到临时文件中,等MySQL 找到所
有记录以后,再把临时文件中的记录作一次排序,这再次排序就会增长 Sort_merge_passes
> show global status like 'sort%';
Sort_merge_passes
排序算法已经执行的合并的数量。若是这个变量值较大,能够考虑增长sort_buffer_size变量的值。
缘由:
ORDER BY(不可以使用索引进行排序)
GROUP BY(使用了GROUP BY COLUMN没有使用ORDER BY NULL).
9 文件打开数(open_files)
show global status like 'open_files';
show variables like 'open_files_limit';
(system@127.0.0.1:3306) [(none)]> show variables like 'open_files_limit';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| open_files_limit | 65535 |
+------------------+-------+
(system@127.0.0.1:3306) [(none)]> show global status like 'open%file%';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Open_files | 15 | # 系统当前打开的文件数
| Opened_files | 1988 | # 系统打开过的文件总数
+---------------+-------+
[root@hongquan1 ~]# ulimit -n
1024
ulimit -a
[root@hongquan1 ~]# ulimit -n 65535
[root@hongquan1 ~]# vim /data/mysqldata/3306/my.cnf
mysql soft nproc 65535
mysql hard nproc 65535
mysql soft nofile 65535
mysql hard nofile 65535linux
比较合适的设置:Open_files / open_files_limit * 100% <= 75%
(system@127.0.0.1:3306) [test]> show global status like 'open%';
| Opened_files | 1375 |是否频繁打开文件
| Opened_table_definitions | 599 |是否频繁打开表结构
| Opened_tables | 946 |查看是否频繁打开表git
已经打开的表的数量。若是Opend_tables较大,则须要考虑加大table_open_cache的值
10 表锁状况
show global status like 'table_locks%';
mysql> show global status like 'table_locks%';
+-----------------------+--------+
| Variable_name | Value |
+-----------------------+--------+
| Table_locks_immediate | 133063 |查看当即得到的表的锁的次数
| Table_locks_waited | 0 |查看不能当即得到的表的锁的次数。若是该值较高,而且有性能问题,你应首先优化查询,而后拆分表或使用复制
> show global status like '%row_lock%';
Innodb_current_row_locks
Innodb_deadlocks
(system@127.0.0.1:3306) [test]> show variables like '%deadlocks%';
+----------------------------+-------+
| Variable_name | Value |
+----------------------------+-------+
| innodb_print_all_deadlocks | OFF |
set global innodb_print_all_deadlocks=1
When this option is enabled, information about all deadlocks in InnoDB user transactions is recorded in the mysqld error log算法
mysql> show global status like '%row_lock%';
+-------------------------------+--------+
| Variable_name | Value |
+-------------------------------+--------+
| Innodb_row_lock_current_waits | 0 | 当前正在等待锁定的数量
| Innodb_row_lock_time | 947851 | 从系统启动到如今锁定总时间长度
| Innodb_row_lock_time_avg | 15 | 每次等待所花平均时间
| Innodb_row_lock_time_max | 11007 | 从系统启动到如今等待最长的一次所花的时间
| Innodb_row_lock_waits | 60873 | 系统启动后到如今总共等待的次数
当Table_locks_waited与Table_locks_immediate 的比值较大,则说明咱们的表锁形成的阻塞比较严重,可能须要优化SQL语句,
或者更改存储引擎,亦或者须要调整业务逻辑。固然,具体改善方式必须根据实际场景来判断。而 Innodb_row_lock_waits 较大,
则说明Innodb的行锁也比较严重,且影响了其余线程的正常处理。一样须要查找出缘由并解决。形成Innodb行锁严重的缘由多是
Query 语句所利用的索引不够合理(Innodb行锁是基于索引来锁定的),形成间隙锁过大。也多是系统自己处理能力有限,则需
要从其余方面(如硬件设备)来考虑解决。
innodb_locks_unsafe_for_binlog在RR隔离级别下取消了 gap lock产生的幻读
Select_full_join
链接两个表的条件没有使用索引每每将致使笛卡尔乘积。能够看见Select_full_join>0
mysql> show global status like 'Select_full_join';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| Select_full_join | 20475 |
+------------------+-------+
mysql> show global status like 'innodb_log_waits';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| Innodb_log_waits | 0 |
+------------------+-------+
当Innodb_log_waits值较大时,说明可用log buffer不足,需等待释放次数,数量较大时须要加大innodb_log_buffer_size的值
(system@127.0.0.1:3306) [(none)]> show status like 'innodb_log%';
+---------------------------+----------+
| Variable_name | Value |
+---------------------------+----------+
| Innodb_log_waits | 0 |
| Innodb_log_write_requests | 17145894 |
| Innodb_log_writes | 11845962 |
+---------------------------+----------+sql
11 表扫描状况
show global status like 'handler_read%';
show global status like 'com_select';
表扫描率 = Handler_read_rnd_next / Com_select数据库
mysql> show global status like 'key_read%';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Key_read_requests | 1835 |--索引读请求
| Key_reads | 2 |--从硬盘读
+-------------------+-------+
计算索引未命中的几率key_cache_miss_rate = Key_reads / Key_read_requests * 100%
mysql> show session status like 'Handler_read%';
mysql> show global status like 'handler_read%';
+-----------------------+----------+
| Variable_name | Value |
+-----------------------+----------+
| Handler_read_first | 1216404 | Number of times the first entry was read from an index
| Handler_read_key | 13248681 | Number of requests to read a row based on a key. If this value is high, your tables may be properly indexed for your queries
| Handler_read_last | 169 |
| Handler_read_next | 28391052 | Number of requests to read the next row in key order, incremented if you are querying an index
column with a range constraint or if you are doing an index scan.
| Handler_read_prev | 323 | Number of requests to read the previous row in key order. Mainly used to optimize ORDER BY ... DESC
| Handler_read_rnd | 506725 | Number of requests to read a row based on a fixed position. This value is high if you are doing a lot of queries that require sorting.
| Handler_read_rnd_next | 43682197 | Number of requests to read the next row in the data file. This value is high if you are doing a lot of table scans.vim
Handler_read_first .此选项代表SQL是在作一个全索引扫描,注意是所有,而不是部分,因此说若是存在WHERE语句,这个选项是不会变的。
若是这个选项的数值很大,既是好事也是坏事。说它好是由于毕竟查询是在索引里完成的,而不是数据文件里,说它坏
是由于大数据量时,即便是索引文件,作一次完整的扫描也是很费时间的。
Handler_read_key 此选项数值若是很高,那么恭喜你,你的系统高效的使用了索引,一切运转良好
Handler_read_last的原意:The number of requests to read the last key in an index. With ORDER BY,
the server will issue a first-key request followed by several next-key requests, whereas with ORDER BY DESC,
the server will issue a last-key request followed by several previous-key requests. This variable was added in MySQL 5.6.1.
Handler_read_next 的原意:The number of requests to read the next row in key order. This value is incremented if
you are querying an index column with a range constraint or if you are doing an index scan.
此选项代表在进行索引扫描时,按照索引从数据文件里取数据的次数
Handler_read_prev 的原意:The number of requests to read the previous row in key order. This read method is mainly used to optimize ORDER BY ... DESC.
此选项代表在进行索引扫描时,按照索引倒序从数据文件里取数据的次数,通常就是ORDER BY ... DESC。注意Handler_read_next是ORDER BY ... ASC的方式取数据。
Handler_read_rnd 就是查询直接操做了数据文件,不少时候表现为没有使用索引或者文件排序
Handler_read_rnd_next 表示“在数据文件中读下一行的请求数。若是你正进行大量的表扫描,该值较高。一般说明你的表索引不正确或写入的查询没有利用索引。
=====
Handler_read_first 表明读取索引头的次数,若是这个值很高,说明全索引扫描不少。
Handler_read_key表明一个索引被使用的次数,若是咱们新增长一个索引,能够查看Handler_read_key是否有增长,若是有增长,说明sql用到索引。
Handler_read_next 表明读取索引的下列,通常发生range scan。
Handler_read_prev 表明读取索引的上列,通常发生在ORDER BY … DESC。
Handler_read_rnd 表明在固定位置读取行,若是这个值很高,说明对大量结果集进行了排序、进行了全表扫描、关联查询没有用到合适的KEY。
Handler_read_rnd_next 表明进行了不少表扫描,查询性能低下。
=====
log_timestamps --5.7默认的值UTC,会出现log的时间戳比now晚8个小时
修改set global log_timestamps=system;
my.cnf,log_timestamps=SYSTEM
修改全站搜索
修改my.ini(my.cnf) ,在 [mysqld] 后面加入一行“ft_min_word_len=1”,而后 重启Mysql,再登陆网站后台(模块管理->全站搜索)重建全文索引。
记录慢查询sql语句,修改my.ini(my.cnf),添加以下代码
show variables like '%log_output%';
set global log_output='TABLE';
select * from mysql.slow_log;
#log-slow-queries
long_query_time = 1 #是指 执行超过多久的 sql 会被 log 下来
log-slow-queries = E:/wamp /logs/slow.log #设置把日志写在那里,能够为空,系统会给一个缺省的文件
#log-slow-queries = /var /youpath/slow.log linux下 host_name-slow.log
log-queries-not-using-indexes
slow_launch_time Global Default=2
Query_time:语句执行的时间及实际消耗时间 。
Lock_time:包含MDL lock和InnoDB row lock和MyISAM表锁消耗时间的总和及锁等待消耗时间。
Rows_sent:发送给mysql客户端的行数,下面是源码中的解释
Number of rows we actually sent to the client
Rows_examined:InnoDB引擎层扫描的行数,下面是源码中的解释
Rows_affected:涉及到修改的话(好比DML语句)这是受影响的行数。
for DML statements: to the number of affected rows;
for DDL statements: to 0.
Bytes_sent:发送给客户端的实际数据的字节数
Tmp_tables:临时表的个数。
Tmp_disk_tables:磁盘临时表的个数。
Tmp_table_sizes:临时表的大小。
mysql> set global general_log=on;
mysql> set global general_log=off;
mysql>set global general_log_file='/tmp/general.lg'; #设置路径
mysql>set global log_output='table'
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
mysql> show variables like 'key_buffer_size';
+-----------------+---------+
| Variable_name | Value |
+-----------------+---------+
| key_buffer_size | 8388608 |
+-----------------+---------+
1 row in set (0.03 sec)
thread_stack = 256K (每一个线程的大小)
sort_buffer_size = 6M 查询排序时所能使用的缓冲区大小。注意:该参数对应的分配内存是每链接独占!mysql须要查询排序时分配该内存,指定大小。
read_buffer_size = 4M 读查询操做所能使用的缓冲区大小。在查询须要时才分片指定内存的大小
read_rnd_buffer_size mysql在查询须要时才分配须要的大小。This variable is used for reads from MyISAM tables, and, for any storage engine, for Multi-Range Read optimization.
join_buffer_size = 8M 联合查询操做所能使用的缓冲区大小,,该参数对应的分配内存也是每一个链接独享!
myisam_sort_buffer_size = 64M (myisam引擎排序缓冲区的大小)The size of the buffer that is allocated when sorting MyISAM indexes during a REPAIR TABLE or when
creating indexes with CREATE INDEX or ALTER TABLE
table_cache = 512 (缓存数据表的数量,避免重复打开表的开销)
thread_cache_size = 64 缓存可重用线程数,减少建立新线程的开销)
query_cache_size = 64M 指定MySQL查询缓冲区的大小。能够经过在MySQL控制台执行如下命令观察:(全局)
mysql>show variables like '%query_cache%'; mysql 自己是有对sql语句缓存的机制的,合理设置咱们的mysql缓存能够下降数据库的io资源。
#
query_cache_type=0 查 询缓存的方式(默认是 ON)
query_cache_size=0 若是你但愿禁用查询缓存,设置 query_cache_size=0。禁用了查 询缓存,将没有明显的开销
做用:该参数用于控制MySQL query cache的内存大小;若是MySQL开启query cache,再执行每个query的时候会先锁住query cache,
而后判断是否存在query cache中,若是存在直接返回结果,若是不存在,则再进行引擎查询等操做
同时insert、update和delete这样的操做都会将query cahce失效掉,这种失效还包括结构或者索引的任何变化
cache失效的维护代价较高,会给MySQL带来较大的压力,因此当咱们的数据库不是那么频繁的更新的时候
uery cache是个好东西,可是若是反过来,写入很是频繁,并集中在某几张表上的时候,那么query cache lock的锁机制会形成很频繁的锁冲突,
对于这一张表的写和读会互相等待query cache lock解锁,致使select的查询效率降低。
现象:数据库中有大量的链接状态为checking query cache for query、Waiting for query cache lock、storing result in query cache;
query_cache_limit 不缓存大于这个值的结果。(缺省为 1M) 查询缓存的统计信息
# > SHOW VARIABLES LIKE '%query_cache%';
# > SHOW STATUS LIKE 'Qcache%';
# 若是Qcache_lowmem_prunes的值很是大,则代表常常出现缓冲不够的状况;
#若是Qcache_hits的值很是大,则代表查询缓冲使用很是频繁,若是该值较小反而会影响效率,那么能够考虑不用查询缓冲;
Qcache_free_blocks,如 果该值很是大,则代表缓冲区中碎片不少
thread_cache_size = 64 能够复用的保存在中的线程的数量。若是有,新的线程从缓存中取得,
当断开链接的时候若是有空间,客户的线置在缓存中。若是有不少新的线程,为了提升性 能能够这个变量值。经过比较 Connections 和 Threads_created 状态的变量,能够看到这个变量的做用
max_connections = 1000 指定MySQL容许的最大链接进程数。若是在访问论坛时常常出现Too Many Connections的错误提示,则须要增大该参数值。
wait_timeout = 10 指定一个请求的最大链接时间,对于4GB左右内存的服务器能够设置为5-10。
skip-networking 开启该选项能够完全关闭MySQL的TCP/IP链接方式,若是WEB服务器是以远程链接的方式访问MySQL数据库服务器则不要开启该选项!不然将没法正常链接!
long_query_time = 10 (设定慢查询的时间)
log-slow-queries =
log-queries-not-using-indexes
(system@127.0.0.1:3306) [test]> show status where Variable_name like 'Threads_%';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_cached | 7 |
| Threads_connected | 46 |
| Threads_created | 58 |
| Threads_running | 2 |
+-------------------+-------+
mysql> show global status like 'Thread%';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_cached | 11 | 线程缓存内的线程的数量
| Threads_connected | 22 | 当前打开链接的数量
| Threads_created | 33 | 建立用来处理链接的线程数。若是Threads_created较大,须要增长thread_cache_size的值。thread cache命中率计算方法Thread_cache_hits = (1 - Threads_created / Connections) * 100%
| Threads_running | 3 |
+-------------------+-------+
若是咱们在MySQL服务器配置文件中设置了thread_cache_size,当客户端断开以后,服务器处理此客户的线程将会缓存起来以响应下一个客户而不是
销毁(前提是缓存数未达上限)。Threads_created表示建立过的线程数,若是发现Threads_created值过大的话,代表 MySQL服务器一直在建立线程,
这也是比较耗资源,能够适当增长配置文件中thread_cache_size值,查询服务器 thread_cache_size配置
mysql> show variables like 'thread_cache_size';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| thread_cache_size | 28 |
mysql> show global status like 'qcache%';
+-------------------------+---------+
| Variable_name | Value |
+-------------------------+---------+
| Qcache_free_blocks | 1 |
| Qcache_free_memory | 1031376 |
| Qcache_hits | 0 |
| Qcache_inserts | 0 |
| Qcache_lowmem_prunes | 0 |
| Qcache_not_cached | 2322582 |
| Qcache_queries_in_cache | 0 |
| Qcache_total_blocks | 1 |
+-------------------------+---------+
MySQL查询缓存变量解释:
Qcache_free_blocks:缓存中相邻内存块的个数。数目大说明可能有碎片。FLUSH QUERY CACHE会对缓存中的碎片进行整理,从而获得一个空闲块。
Qcache_free_memory:缓存中的空闲内存。
Qcache_hits:每次查询在缓存中命中时就增大
Qcache_inserts:每次插入一个查询时就增大。命中次数除以插入次数就是不中比率。
Qcache_lowmem_prunes:缓存出现内存不足而且必需要进行清理以便为更多查询提供空间的次数。这个数字最好长时间来看;若是这个数字在不断增加,
就表示可能碎片很是严重,或者内存不多。(上面的 free_blocks和free_memory能够告诉您属于哪一种状况)
Qcache_not_cached:不适合进行缓存的查询的数量,一般是因为这些查询不是 SELECT 语句或者用了now()之类的函数。
Qcache_queries_in_cache:当前缓存的查询(和响应)的数量。
Qcache_total_blocks:缓存中块的数量。
[ERROR] /usr/local/mysql/bin/mysqld: Incorrect key file for table '/data/mysqldata/3306/tmp/#sql_cfd4_3.MYI'; try to repair it
tmp_table_size = 256M
mysql> show global status like 'created_tmp%';
+-------------------------+--------+
| Variable_name | Value |
+-------------------------+--------+
| Created_tmp_disk_tables | 1461 | Created_tmp_disk_tables / Created_tmp_tables * 100% <= 25%
| Created_tmp_files | 15 |
| Created_tmp_tables | 269830 |
mysql> show variables where Variable_name in ('tmp_table_size', 'max_heap_table_size');
+---------------------+----------+
| Variable_name | Value |
+---------------------+----------+
| max_heap_table_size | 33554432 |
| tmp_table_size | 16777216 | --32mb如下的临时表才能彻底放内存,超过就会用到硬盘临时表
max_connections = 768 指定MySQL容许的最大链接进程数。若是在访问论坛时常常出现Too Many Connections的错误提示,则须要增大该 参数值。
extra_port=13306 若是使用extra_port参数,MySQL max_connection个链接所有被占用,DBA能够以管理员权限建立 extra_max_connections+1个链接
mysql> show variables like 'max_connections%';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 2000 |
+-----------------+-------+
Max_used_connections / max_connections * 100% ≈ 85%
max_connect_errors = 10000000
max_connections=1024 是指整个mysql服务器的最大链接数
max_user_connections=256 是指每一个数据库用户的最大链接数
max_connect_errors=65536
timeout 只是针对空闲会话有影响
interactive_timeout:120 服务器关闭交互式(CLIENT_INTERACTIVE)链接前等待活动的秒数。交互式客户端定义为
在mysql_real_connect()中使用CLIENT_INTERACTIVE选项的客户端。
wait_timeout = 120 指定一个请求的最大链接时间,对于4GB左右内存的服务器能够设置为5-10。
MySQL客户端的数据库链接闲置最大时间值,说得比较通俗一点,就是当你的MySQL链接闲置超过必定时间后将会被强行关闭
致使MySQL超过最大链接数历来没法新建链接致使“Too many connections”的错误
mysql中的sleep线程最多睡120秒,就会被强行关闭
local_wait_timeout 以秒为单位设定全部SQL语句等待获取元数据锁(metadata lock)的超时时长,默认为31536000(1年
其影响的SQL语句包括用于表、视图、存储过程和存储函数的DML和DDL语句,以及LOCK TABLES、FLUSH TABLES WITH READ LOCK和HANDLER语句等
| interactive_timeout | 120 |
| wait_timeout | 120 |
(system@127.0.0.1:3306) [(none)]> show full processlist;
ERROR 2013 (HY000): Lost connection to MySQL server during query
(system@127.0.0.1:3306) [(none)]> show full processlist;
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
(system@127.0.0.1:3306) [(none)]> set global interactive_timeout = 3660;
| interactive_timeout | 3660 |
| wait_timeout | 3660 |
交互式会话的timeout时间受global级别的interactive_timeout影响。所以要修改非交互模式下的timeout,必须同时修改interactive_timeout的值
非交互模式下,wait_timeout参数继承global级别的wait_timeout
mysql> show variables like '%wait_timeout%';
+--------------------------+----------+
| Variable_name | Value |
+--------------------------+----------+
| innodb_lock_wait_timeout | 5 |
| lock_wait_timeout | 31536000 |
| wait_timeout | 28800 |
+--------------------------+----------+
innodb_lock_wait_timeout:指的是事务等待获取资源等待的最长时间,超过这个时间还未分配到资源则会返回应用失败
参数支持范围为Session和Global,且支持动态修改,因此能够经过两种方法修改;
set innodb_lock_wait_timeout=100;
set global innodb_lock_wait_timeout=100;
注意global的修改对当前线程是不生效的,只有创建新的链接才生效
set global interactive_timeout = 120;
set global wait_timeout = 120;
show session variables like '%timeout%';
set session wait_timeout=10;#超时后,仍是取global的值
set session interactive_timeout=10;
timeout值,对于处于运行状态SQL语句是否起效(便是否等价于执行超时)? A:由下例可见SQL正在执行状态的等待时间不计入timeout时间。即SQL运行再久也不会由于timeout的配置而中断
同一个session中,wait_timeout 和 interacitve_timeout是否都会生效。 A:只有wait_timeout 会真正起到超时限制的做用
global timeout和session timeout是否都会做为超时判断依据? A:只有session级别 timeout 会起做用。即一个session开始后,不管如何修改global级别的timeout都不会影响该session
超时时间只对非活动状态的connection进行计算。
超时时间只以session级别的wait_timeout 为超时依据,global级别只决定session初始化时的超时默认值。
交互式链接的wait_timeout 继承于global的interactive_timeout。非交互式链接的wait_timeout继承于global的wait_timeout
继承关系和超时对 TCP/IP 和 Socket 链接均有效果
lock_wait_timeout:This timeout applies to all statements that use metadata locks,mysql的mdl锁
These include DML and DDL operations on tables, views, stored procedures, and stored functions,
as well as LOCK TABLES, FLUSH TABLES WITH READ LOCK, and HANDLER statements
此超时适用于使用元数据锁的全部语句。 这些包括对表,视图,存储过程和存储函数的DML和DDL操做,
以及LOCK TABLES,FLUSH TABLES WITH READ LOCK和HANDLER语句。
此超时不适用于对mysql数据库中系统表的隐式访问,例如由GRANT或REVOKE语句或表记录语句修改的受权表。
该超时功能适用于直接访问的系统表,例如使用SELECT或UPDATE。
lock_wait_timeout=120
The timeout value applies separately for each metadata lock attempt. A given statement can
require more than one lock, so it is possible for the statement to block for longer than the
lock_wait_timeout value before reporting a timeout error.
--5.7
This variable specifies the timeout in seconds for attempts to acquire metadata locks.
The permissible values range from 1 to 31536000 (1 year). The default is 31536000
connect_timeout Default=10
mysql> set global connect_timeout=60;
The number of seconds that the mysqld server waits for a connect packet before responding with Bad handshake. The default value is 10 seconds.
Increasing the connect_timeout value might help if clients frequently encounter errors of the form Lost connection to MySQL server at 'XXX', system error: errno.
当一个链接上来,在三次握手的时候出现错误,mysql服务器会等待一段时间客户端进行从新链接,connect_timeout就是服务端等待重连的时间了
net_write_timeout 做用:等待将一个block发送给客户端的超时时间。 现象:参数设置太小可能致使客户端报错
the last packet successfully received from the server was milliseconds ago,the last packet sent successfully to the server was milliseconds ago。
建议:该参数在RDS中默认设置为60S,通常在网络条件比较差的时,或者客户端处理每一个block耗时比较长时,因为net_write_timeout设置太小致使的链接中断很容易发生,建议增长该参数的大小
| net_write_timeout | 60 |
set @@global.net_write_timeout=500;
skip-grant-tables :不使用mysql数据库里的信息来进行访问控制(警告:这将容许用户任何用户去修改任何数据库)。
skip-networking 开启该选项能够完全关闭MySQL的TCP/IP链接方式,若是WEB服务器是以远程链接的方式访问MySQL数据库服务器则不要开 启该选项!不然将没法正常链接!
---------------
skip-locking # 避免MySQL的外部锁定,减小出错概率加强稳定性。
skip-name-resolve 禁止MySQL对外部链接进行DNS解析,使用这一选项能够消除MySQL进行DNS 解析的时间。但须要注意,
若是开启该选项,则全部远程主机链接受权都要使用IP地址方式,不然MySQL将没法正常处理链接请求!
skip-ssl Do not use secure connection
back_log = 500 要求 MySQL 能有的链接数量。当主要MySQL线程在一个很短期内获得很是多的链接请求,
这就起做用,而后主线程花些时间(尽管很短)检查链接而且启动一个新线程。
不须要配置 =50 + (max_connections / 5),===50+ 3000/5=650
Default Value -1 (autosized)
back_log值指出在MySQL暂时中止回答新请求以前的短期内多少个请求能够被存在堆栈中。只有若是指望在一个短期内有不少链接,
你须要增 加它,换句话说,这值对到来的TCP/IP链接的侦听队列的大小。
你的操做系统在这个队列大小上有它本身的限制。试图设定 back_log高于你的操做系统的限制将是无效的。
当你观察你的主机进程列表,发现大量 264084 | unauthenticated user | xxx.xxx.xxx.xxx | NULL | Connect | NULL | login |
NULL 的待链接进程时,就要加大 back_log 的值了。默认数值是50,我把它改成500。
做用:MySQL每处理一个链接请求的时候都会对应的建立一个新线程与之对应,那么在主线程建立新线程期间,若是前端应用有
大量的短链接请求到达数据库,MySQL 会限制此刻新的链接进入请求队列,由参数back_log控制,若是等待的链接数量超过back_log,
则将不会接受新的链接请求,因此若是须要MySQL可以处理大量的短链接,须要提升此参数的大小。 现象:若是参数太小可能会致使应用报错
SQLSTATE[HY000] [2002] Connection timed out;
# ps aux|wc -l
innodb_autoinc_lock_mode
InnoDB为了解决自增主键锁表的问题,引入了参数innodb_autoinc_lock_mode,用于控制自增主键的锁机制,该参数能够设置的值为0/1/2,
RDS 默认的参数值为1,表示InnoDB使用轻量级别的mutex锁来获取自增锁,替代最原始的表级锁,可是在load data(包括:INSERT …
SELECT, REPLACE … SELECT)场景下会使用自增表锁,这样会则可能致使应用在并发导入数据出现死锁。 现象:若是应用并发使用
load data(包括:INSERT … SELECT, REPLACE … SELECT)导入数据的时候出现死锁:
RECORD LOCKS space id xx page no xx n bits xx index PRIMARY of table xx.xx trx id xxx lock_mode X insert intention
waiting. TABLE LOCK table xxx.xxx trx id xxxx lock mode AUTO-INC waiting;
建议:建议将参数设置改成2,则表示全部状况插入都使用轻量级别的mutex锁(只针对row模式),这样就能够避免auto_inc的死锁,
同时在INSERT … SELECT 的场景下会提高很大的性能(注意该参数设置为2,binlog的格式须要设置为row)。
open_files_limit (打开文件数,linux的系统默认是1024)==my.cnf不配置,取值[root@hongquan soft]# ulimit -n
open_files_limit值总结以下:
my.cnf里若是配置了open_files_limit
open_files_limit最后取值为 配置文件 open_files_limit,max_connections*5, wanted_files= 10+max_connections+table_cache_size*2 三者中的最大值。
若是my.cnf里若是没配置了open_files_limit
open_files_limit最后取值为max_connections*5,10+max_connections+table_cache_size*2,ulimit -n中的最大者
/etc/sysctl.conf参数解释
http://www.cnblogs.com/goodspeed/p/3587195.html
mysql> show variables like '%dump%';
+-------------------------------------+-------+
| Variable_name | Value |
+-------------------------------------+-------+
| innodb_buffer_pool_dump_at_shutdown | OFF |
| innodb_buffer_pool_dump_now | OFF |
--开启,当mysql关闭的时候,把热点数据缓存到磁盘文件,下次启动的时候,自动加入内存中
[root@hongquan soft]# vim /etc/security/limits.conf
mysql soft nproc 65535
mysql hard nproc 65535
mysql soft nofile 65535
mysql hard nofile 65535
[root@hongquan soft]# source /etc/profile
[mysql@hongquan 3306]$ ulimit -a
mysqld --verbose --help
mysqld --no-defaults --verbose --help
mysql> show variables like '%open_files_limit%';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| open_files_limit | 1024 |
[root@hongquan soft]# ps -ef|grep mysql
mysql 16581 15233 0 00:45 pts/2 00:00:09 /usr/local/mysql/bin/mysqld
[root@hongquan soft]# lsof -p 16581 |wc -l
57
ls -lh /proc/16581/fd|wc -l
[root@hongquan soft]# cat /proc/16581/limits
[root@hongquan soft]# ulimit -n
1024
mysql> show variables like '%max_connections%';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 214 |
mysql> show variables like '%table_open_cache%';
+----------------------------+-------+
| Variable_name | Value |
+----------------------------+-------+
| table_open_cache | 400 |#1024
| table_open_cache_instances | 1 |
wanted_files= 10+max_connections+table_cache_size*2;=10+214+400*2=
max_connections*5=214*5
open_files_limit 在my.cnf配置时候的值
若是不配置就是wanted_files max_connections*5 和ulimit -n中的最大者
key_buffer_size = 8M Size of buffer used for index blocks for MyISAM tables
# key_buffer_size指定用于索引的缓冲区大小,增长它可获得更好处理的索引(对全部读和多重写),到你能负担得起那样多。
若是你使它太大,系 统将开始换页而且真的变慢了。对于内存在4GB左右的服务器该参数可设置为384M或512M。经过检查状态 值Key_read_requests和Key_reads,能够知道key_buffer_size设置是否合理。
比例key_reads / key_read_requests应该尽量的低,至少是1:100,1:1000更好(上述状态值可使用SHOW STATUS LIKE 'key_read%'得到)。注意:该参数值设置的过大反而会是服务器总体效率下降!
(system@127.0.0.1:3306) [sys]> SHOW STATUS LIKE 'key_read%';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Key_read_requests | 126 |
| Key_reads | 5 |
使用排序
mysql> show global status like 'sort%';
+-------------------+--------+
| Variable_name | Value |
+-------------------+--------+
| Sort_merge_passes | 0 |
| Sort_range | 20576 |
| Sort_rows | 830484 |
| Sort_scan | 637562 |
+-------------------+--------+
Sort_merge_passes 包括两步。MySQL 首先会尝试在内存中作排序,使用的内存大小由系统变量 Sort_buffer_size 决定,
若是它的大小不够把全部的记录都读到内存中,MySQL 就会把每次在内存中排序的结果存到临时文件中,等 MySQL 找到所
有记录以后,再把临时文件中的记录作一次排序。这再次排序就会增长 Sort_merge_passes。实际上,MySQL 会用另外一个
临时文件来存再次排序的结果,因此一般会看到 Sort_merge_passes 增长的数值是建临时文件数的两倍。由于用到了临时
文件,因此速度可能会比较慢,增长 Sort_buffer_size 会减小 Sort_merge_passes 和 建立临时文件的次数。但盲目的
增长 Sort_buffer_size 并不必定能提升速度
开启慢查询日志( slow query log )
慢查询日志对于跟踪有问题的查询很是有用。它记录全部查过long_query_time的查询,若是须要,还能够记录不使用索引的记录。下面是一个 慢查询日志的例子:
开启慢查询日志,须要设置参数log_slow_queries、long_query_times、log-queries-not-using- indexes。
log_slow_queries指定日志文件,若是不提供文件名,MySQL将本身产生缺省文件名。long_query_times指定慢查询的 阈值,缺省是10秒。
log-queries-not-using-indexes是4.1.0之后引入的参数,它指示记录不使用索引的查询。设置 long_query_time=10
使用show status命令
aborted_clients 客户端非法中断链接次数
aborted_connects 链接mysql失败次数
com_xxx xxx命令执行次数,有不少条
connections 链接mysql的数量 The number of connection attempts (successful or not) to the MySQL server.
Created_tmp_disk_tables 在磁盘上建立的临时表
Created_tmp_tables 在内存里建立的临时表
Created_tmp_files 临时文件数
Key_read_requests The number of requests to read a key block from the cache
Key_reads The number of physical reads of a key block from disk
Max_used_connections 同时使用的链接数
Open_tables 开放的表
Open_files 开放的文件
Opened_tables 打开过的表的数量
mysql> show global status like 'open%tables%';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Open_tables | 300 |
| Opened_tables | 313 |
Open_tables / Opened_tables * 100% >= 85%
Open_tables / table_cache * 100% <= 95%
Questions 提交到server的查询数
Sort_merge_passes 若是这个值很大,应该增长my.cnf中的sort_buffer值
Uptime 服务器已经工做的秒数
提高性能的建议:
1.若是opened_tables太大,应该把my.cnf中的table_cache变大
2.若是Key_reads太大,则应该把my.cnf中key_buffer_size变大.能够用 Key_reads/Key_read_requests计算出cache失败率
3.若是Handler_read_rnd太大,则你写的SQL语句里不少查询都是要扫描整个表,而没有发挥索引的键的做用
4.若是Threads_created太大,就要增长my.cnf中thread_cache_size的值.能够用 Threads_created/Connections计算cache命中率
5.若是Created_tmp_disk_tables太大,就要增长my.cnf中tmp_table_size的值,用基于内存的临时表代替基 于磁盘的
set profiling =1;
insert
mysql> show profiles;
mysql> show profile for query 35;
(system@127.0.0.1:3306) [(none)]> show status like 'Innodb_buffer_pool_%';
+---------------------------------------+--------------------------------------------------+
| Variable_name | Value |
+---------------------------------------+--------------------------------------------------+
| Innodb_buffer_pool_dump_status | Dumping of buffer pool not started |
| Innodb_buffer_pool_load_status | Buffer pool(s) load completed at 180416 1:33:20 |
| Innodb_buffer_pool_resize_status | |
| Innodb_buffer_pool_pages_data | 63149 |--缓存数据的页数量
| Innodb_buffer_pool_bytes_data | 1034633216 |--当前buffer pool缓存的数据大小,包括脏数据
| Innodb_buffer_pool_pages_dirty | 28 |--缓存数据的页数量
| Innodb_buffer_pool_bytes_dirty | 458752 |--缓存的脏数据大小
| Innodb_buffer_pool_pages_flushed | 3096734 |--刷新页请求数量
| Innodb_buffer_pool_pages_free | 2048 |--空闲页数量
| Innodb_buffer_pool_pages_misc | 331 |--用于维护诸如行级锁或自适应hash索引的内存页=总页数-空闲页-使用的页数量
| Innodb_buffer_pool_pages_total | 65528 |--总共65528个pages
| Innodb_buffer_pool_read_ahead_rnd | 0 |--记录进行随机读的时候产生的预读次数
| Innodb_buffer_pool_read_ahead | 504902 |--预读的页数
| Innodb_buffer_pool_read_ahead_evicted | 0 |--预读的页数,可是没有被读取就从缓冲池中被替换的页的数量,通常用来判断预读的效率。
| Innodb_buffer_pool_read_requests | 228730848 |--read请求228730848
| Innodb_buffer_pool_reads | 8219 |--直接从磁盘读取数据的逻辑读次数,缓存未命中
| Innodb_buffer_pool_wait_free | 0 |--缓存中没有空闲页知足当前请求,必须等待部分页回收或刷新,记录等待次数
| Innodb_buffer_pool_write_requests | 108371241 |--向缓存的写数量
innodb_buffer_pool_size is configured to 50 to 75 percent of system memory
innodb_buffer_pool_size:主要针对InnoDB表性能影响最大的一个参数。功能与Key_buffer_size同样。InnoDB占用的内存,
除innodb_buffer_pool_size用于存储页面缓存数据外,另外正常状况下还有大约8%的开销,主要用在每一个缓存页帧的描述、adaptive hash等数据结构
另外InnoDB和 MyISAM 存储引擎不一样, MyISAM 的 key_buffer_size 只能缓存索引键,而 innodb_buffer_pool_size 却能够缓存数据块和索引键。
适当的增长这个参数的大小,能够有效的减小 InnoDB 类型的表的磁盘 I/O
当咱们操做一个 InnoDB 表的时候,返回的全部数据或者去数据过程当中用到的任何一个索引块,都会在这个内存区域中走一遭。
能够经过 (Innodb_buffer_pool_read_requests – Innodb_buffer_pool_reads) / Innodb_buffer_pool_read_requests * 100% 计算缓存命中率,
并根据命中率来调整 innodb_buffer_pool_size 参数大小进行优化。值能够用如下命令查
innodb_buffer_pool_instances=8 将innodb_buffer_pool划分为不一样的instance,每一个instance独立的LRU、FLUSH、FREE
InnoDB_buffer_pool_instances:8 (platform dependent) 5.6.6
innodb_log_file_size=512M 官方文档建议最好不要超过innodb_log_files_in_group*innodb_log_file_size的0.75, innodb_log_files_in_group的default值为2.
logfile大小对于性能的影响主要体如今checkpoint上
innodb_log_files_in_group=3
innodb_log_group_home_dir
innodb_log_buffer_size=200M 默认8388608先写入innodb_log_buffer,buffer写满或事务提交,刷新数据,大事务频繁,增长innodb_log_buffer_size大小
innodb_thread_concurrency=(64-128) ,default 0 表示没有并发线程的限制,全部请求都会直接请求线程执行,innodb内部本身控制 kernel_mutex竞争
设置太高值,可能会由于系统资源内部争夺致使性能降低,
并发查询和并发链接
innodb_io_capacity=1000 innodb每秒后台进程处理IO操做的数据页上限,default 200,测试的虚拟机,200或者100
innodb_buffer_pool_size总的io处理能力上限
innodb_buffer_pool_instances分割成多个内存块时,每一个内存块的IO处理能力为:innodb_io_capacity/innodb_buffer_pool_instances
对于个别5400转或7200转硬盘系统上,可能下降值的100前者默认。
innodb_flush_neighbors This option optimizes I/O for rotational storage devices. Disable it for non-rotational storage or a mix of rotational and non-rotational storage.
innodb_io_capacity The default setting of 200 is generally sufficient for a lower-end non-rotational storage device. For higher-end, bus-attached devices, consider a higher setting such as 1000
innodb_io_capacity_max The default value of 2000 is intended for workloads that use non-rotational storage. For a highend, bus-attached non-rotational storage device, consider a higher setting such as 2500
innodb_lru_scan_depth 每一个缓冲池实例,缓冲池LRU在多大程度上列出了页面清理线程These options primarily help write-intensive workloads. With heavy DML activity, flushing can fall
behind if it is not aggressive enough, resulting in excessive memory use in the buffer pool or, disk
writes due to flushing can saturate your I/O capacity if that mechanism is too aggressive
Optimizing InnoDB Disk I/O
The configuration options innodb_flush_neighbors and innodb_lru_scan_depth let you finetune aspects of the flushing process for the InnoDB buffer pool.
innodb_flush_neighbors 在buffer pool中刷新脏页时是否刷新其余脏页,在hdd磁盘上,刷新邻居页面会减小磁盘的io消耗,在ssd来讲,这个能够禁用。
(system@127.0.0.1:3306) [(none)]> SHOW GLOBAL VARIABLES LIKE 'innodb_lru_scan_depth';
+-----------------------+-------+
| Variable_name | Value |
+-----------------------+-------+
| innodb_lru_scan_depth | 1024 |
+-----------------------+-------+
而从MySQL 5.6版本,也就是InnoDB1.2.x版本开始,这个检查被放在了一个单独的Page Cleaner线程中进行,而且用户能够经过参数innodb_lru_scan_depth控制LRU列表中可用页的数量,该值默认为1024
innodb_max_dirty_pages_pct=60 default 75 InnoDB试着从缓冲池刷新数据,使脏页的百分比不超过这个值
innodb从innodb buffer中刷新脏页的比例
刷新脏页,产生checkpoint
脏页刷新innodb_max_dirty_pages_pct * innodb_io_capacity
innodb_flush_method=O_DIRECT 定义用于刷新数据到InnoDB数据文件和日志文件的方法,这可能会影响I / O吞吐量。
O_DSYNC:使用O_SYNC打开和刷新log文件,使用fsync()刷新数据文件。
O_DIRECT:使用O_DIRECT打开数据文件,使用fsync()刷新日志文件和数据文件
在raid设备上,为了不数据被innodb_buffer和raid屡次cache,设置为O_DIRECT方式
fdatasync模式:写数据时,write这一步并不须要真正写到磁盘才算完成(可能写入到操做系统buffer中就会返回完成),
真正完成是flush操做,buffer交给操做系统去flush,而且文件的元数据信息也都须要更新到磁盘。
O_DSYNC模式:写日志操做是在write这步完成,而数据文件的写入是在flush这步经过fsync完成
O_DIRECT模式:数据文件的写入操做是直接从mysql innodb buffer到磁盘的,并不用经过操做系统的缓冲,
而真正的完成也是在flush这步,日志(redo log)仍是要通过OS缓冲
innodb_file_per_table=1 Permitted Values (>= 5.6.6) Default ON 不一样的表空间能够灵活设置数据目录的地址 避免共享表空间产生的IO竞争
innodb_flush_log_at_trx_commit=1 default 1
0:每秒将log buffer的内容写事务日志而且刷新到磁盘;
1:每一个事务提交后,将log_buffer的内容写事务日志并数据磁盘;---大量事务提交,磁盘io增长
2:每一个事务提交,将log_buffer内容写事务日志,但不进行数据刷盘,在整个操做系统 挂了时才可能丢数据,通常不会丢失超过1-2秒的更新。
sync_binlog=1 非核心数据库,能够不设置为1,提升性能
双1模式,即:innodb_flush_log_at_trx_commit = 1,sync_binlog = 1,这样主备的数据是一致的,不会丢失数据
sync_binlog=1 Mysql在提交事务时调用MYSQL_LOG::write完成写binlog,并根据sync_binlog决定是否进行刷盘。
默认值是0,即不刷盘,从而把控制权让给OS。若是设为1,则每次提交事务,就会进行一次刷盘;这对性能有影响
(5.6已经支持binlog group),因此不少人将其设置为100
innodb_flush_log_at_trx_commit=1 该参数控制innodb在提交事务时刷redo log的行为。默认值为1,即每次提交事务,
都进行刷盘操做。为了下降对性能的影响,在不少生产环境设置为2,甚至0
innodb_support_xa=1 用于控制innodb是否支持XA事务的2PC,默认是TRUE。若是关闭,则innodb在prepare阶段就什么
也不作;这可能会致使binlog的顺序与innodb提交的顺序不一致(好比A事务比B事务先写binlog,
可是在innodb内部却可能A事务比B事务后提交),这会致使在恢复或者slave产生不一样的数据。
binlog_row_image='minimal' 5.7
上面3个参数不一样的值会带来不一样的效果。三者都设置为1(TRUE),数据才能真正安全
sync_binlog非1,可能致使binlog丢失(OS挂掉),从而与innodb层面的数据不一致
innodb_flush_log_at_trx_commit非1,可能会致使innodb层面的数据丢失(OS挂掉),从而与binlog不一致。
skip-external-locking:default on,每一个进程若要访问数据表,则必须等待以前的进程完成操做并解除锁定。
lower_case_table_names 数据库大小写是否敏感,默认=0 (区分大小写),
设置为1后,表名能够正常忽略大小写,可是若是是为0时建立的数据库如Test这样,而后修改成1,进行查询test是查询不到的,务必谨记
safe-user-create 只有在mysql.user数据库表上拥有INSERT权限的用户才能使用GRANT命令; 这是一种双保险机制(此用户还必须具有GRANT权限才能执行GRANT命令)
GRANT INSERT(user) ON mysql.user TO 'user_name'@'host_name';
local-infile=1 要支持命令load data local infile,应当在/etc/mysql/my.cnf中添加这样的设置:
transaction-isolation
mysql> show variables like 'tx_isolation';
+---------------+----------------+
| Variable_name | Value |
+---------------+----------------+
| tx_isolation | READ-COMMITTED | REPEATABLE-READ
READ-COMMITTED 读取提交内容(oracle默认)
REPEATABLE-READ 可重读(mysql默认)
max_binlog_size=1073741824
max_binlog_cache_size
If a transaction requires more than this many bytes of memory, the server generates a Multi-statement
transaction required more than 'max_binlog_cache_size' bytes of storage error. The minimum value is 4096.
The maximum possible value is 16EB (exabytes). The maximum recommended value is 4GB; this is due to the fact
that MySQL currently cannot work with binary log positions greater than 4GB.
binlog_cache_size 为每一个session 分配的内存,在事务过程当中用来存储二进制日志的缓存,没有什么大事务,
dml也不是很频繁的状况下能够设置小一点,若是事务大并且多,dml操做也频繁,则能够适当的调大一点
mysql> show global status like 'bin%';
+----------------------------+-------+
| Variable_name | Value |
+----------------------------+-------+
| Binlog_cache_disk_use | 0 |
| Binlog_cache_use | 1 |
Binlog_cache_disk_use表示由于咱们binlog_cache_size设计的内存不足致使缓存二进制日志用到了临时文件的次数
Binlog_cache_use 表示 用binlog_cache_size缓存的次数
当对应的Binlog_cache_disk_use 值比较大的时候 咱们能够考虑适当的调高 binlog_cache_size 对应的值
innodb_rollback_on_timeout 该变量默认值为OFF,若是事务由于加锁超时,会回滚上一条语句执行的操做。若是设置ON,则整个事务都会回滚。
a.max_binlog_cache_size 表示的是binlog 可以使用的最大cache 内存大小
当咱们执行多语句事务的时候 全部session的使用的内存超过max_binlog_cache_size的值时
就会报错:“Multi-statement transaction required more than 'max_binlog_cache_size' bytes ofstorage”
b.设置太大的话,会比较消耗内存资源;设置过小又会使用到临时文件即disk
performance_schema (>= 5.6.6) ON
log_slow_admin_statements 包括行政语句的语句写入缓慢慢查询日志。管理报表包括ALTER TABLE,分析表,检查表,建立索引,指数降低,优化表、和维修表。
table_definition_cache (>= 5.6.8) -1 (autosized) 若是你使用大量的表,您能够建立一个大表定义缓存加速的表。须要更少的空间和表定义缓存
复制有关的参数
#replication
master-info-file=Default master.info,默认路径/data/mysqldata/3307/data/master.info
The name to use for the file in which the slave records information about the master.
relay_log 中继日志文件
relay_log_info_file
relay-log-index
slave_type_conversions =ALL_LOSSY,ALL_NON_LOSSY
ALL_SIGNED and ALL_UNSIGNED were added in MySQL 5.6.13 (Bug#15831300).
ALL_LOSSY容许数据截断
ALL_NON_LOSSY不容许数据截断,若是从库类型大于主库类型,是能够复制的,翻过了,就不行了,从库报复制错误,复制终止。
ALL_LOSSY,ALL_NON_LOSSY: 全部容许的转换都会执行,而无论是否是数据丢失。
空值 (不设置) : 要求主从库的数据类型必须严格一致,不然都报错。
skip_slave_start: Default FALSE,默认在启动mysql 的时候启动slave threads 线程,skip-slave-start: DESCRIPTION: If set, slave is not autostarted
slave_exec_mode=STRICT :Default,STRICT (ALL)
slave_load_tmpdir
slave_max_allowed_packet=1073741824
slave_net_timeout=3600:The number of seconds to wait for more data from a master/slave connection before aborting the read. 改为slave_net_timeout=60
slave_parallel_workers=0:Sets the number of slave worker threads for executing replication events (transactions) in parallel.
slave_skip_errors=OFF
sync_master_info
sync_relay_log_info
sync_relay_log 默认值是10000,也就是10000个事物进行一次fdatasync。
skip_name_resolve 关闭dns查找
slave_net_timeout=60 #意味着在没有获得更多数据以后slave等待的时间,默认值3600s
master-connect-retry #意味着每次和主库创建连接重试的等待时间,默认值为60s
master-retry-count #意味着从库同主库创建连接的重试次数,默认86400次
log-slave-updates 这个参数用来配置从服务器的更新是否写入二进制日志
log-slave-updates=1
rpl_semi_sync_master_enabled=1 是否在master节点开启半同步复制,Default OFF
rpl_semi_sync_master_timeout=3 知道master等待响应slave的时间,毫秒,超出时间,将转变为异步复制,Default 10000
rpl_semi_sync_slave_enabled=1 控制slave是否开启半同步复制 Default OFF
rpl_semi_sync_master_clients 显示当前处于半同步模式的slave节点数量
rpl_semi_sync_master_status 标示当前master是否启动半同步模式
rpl_semi_sync_master_no_tx 当前未成功发送到slave节点事务数量
rpl_semi_sync_master_yes_tx 当前已成功发送到slave节点的事务数量
enable_table_relay_info = 1 #开启crash safe功能
relay_log_recovery = 1 #开启crash safe功能 ,默认| relay_log_recovery | OFF |
relay_log_purge = 1 #default no
slave_parallel_threads=16 #并行复制的线程数
relay-log-recovery: Enables automatic recovery of relay log files from master at startup
relay_log_recovery: Whether automatic recovery of relay log files from master at startup is enabled;must be enabled for a crash-safe slave
? replicate-do-db: Tells the slave SQL thread to restrict replication to the specified database
? replicate-do-table: Tells the slave SQL thread to restrict replication to the specified table
? replicate-ignore-db: Tells the slave SQL thread not to replicate to the specified database
? replicate-ignore-table: Tells the slave SQL thread not to replicate to the specified table
? replicate-rewrite-db: Updates to a database with a different name than the original
? replicate-same-server-id: In replication, if set to 1, do not skip events having our server id
? replicate-wild-do-table: Tells the slave thread to restrict replication to the tables that match the specified wildcard pattern
? replicate-wild-ignore-table: Tells the slave thread not to replicate to the tables that match the given wildcard pattern
主上:
rpl_semi_sync_master_enabled:表示主上是否开启半同步复制功能,能够动态修改。可选值:ON\OFF
rpl_semi_sync_master_timeout:为了防止半同步复制中主在没有收到S发出的确认发生堵塞,用来设置超时,超过这个时间值没有收到信息,
则切换到异步复制,执行操做。默认为10000毫秒,等于10秒,这个参数动态可调,表示主库在某次事务中,若是等待时间超过10秒,
那么则降级为异步复制模式,再也不等待SLAVE从库。若是主库再次探测到,SLAVE从库恢复了,则会自动再次回到半同步复制模式。能够设置成1000,即1秒。
rpl_semi_sync_master_wait_for_slave_count:控制slave应答的数量,默认是1,表示master接收到几个slave应答后才commit。
rpl_semi_sync_master_wait_no_slave :当一个事务被提交,可是Master没有Slave链接,这时M不可能收到任何确认信息,但M会在时间限制范围内继续等待。
若是没有Slave连接,会切换到异步复制。是否容许master每一个事务提交后都要等待slave的接收确认信号。默认为on,每个事务都会等待。若是为off,
则slave追遇上后,也不会开启半同步复制模式,须要手工开启。
rpl_semi_sync_master_wait_point:该参数表示半同步复制的主在哪一个点等待从的响应,默认AFTER_SYNC,在获得slave的应答后再commit,可选值AFTER_COMMIT。
从上:
rpl_semi_sync_slave_enabled:表示从上是否开启半同步复制功能,能够动态修改。可选值:ON\OFF
Rpl_semi_sync_master_clients :说明支持和注册半同步复制的已连Slave数。
Rpl_semi_sync_master_net_avg_wait_time :master等待slave回复的平均等待时间,单位毫秒。
Rpl_semi_sync_master_net_wait_time :master总的等待时间。Rpl_semi_sync_master_net_waits :master等待slave回复的的总的等待次数,即半同步复制的总次数,
无论失败仍是成功,不算半同步失败后的异步复制。Rpl_semi_sync_master_no_times :master关闭半同步复制的次数。
Rpl_semi_sync_master_no_tx :master没有收到slave的回复而提交的次数,能够理解为master等待超时的次数,即半同步模式不成功提交数量。
Rpl_semi_sync_master_status :ON是活动状态(半同步),OFF是非活动状态(异步),用于表示主服务器使用的是异步复制模式,仍是半同步复制模式。
Rpl_semi_sync_slave_status :Slave上的半同步复制状态,ON表示已经被启用,OFF表示非活动状态。
Rpl_semi_sync_master_tx_avg_wait_time :master花在每一个事务上的平均等待时间。
Rpl_semi_sync_master_tx_wait_time :master总的等待时间。
Rpl_semi_sync_master_tx_waits :master等待成功的次数,即master没有等待超时的次数,也就是成功提交的次数
Rpl_semi_sync_master_wait_pos_backtraverse :master提交后来的先到了,而先来的尚未到的次数。
Rpl_semi_sync_master_wait_sessions :前有多少个session由于slave的回复而形成等待。Rpl_semi_sync_master_yes_tx :master成功接收到slave的回复的次数,即半同步模式成功提交数量。
SET GLOBAL SQL_SLAVE_SKIP_COUNTER =1;
--slave-skip-errors=1062,1053
--slave-skip-errors=all
--slave-skip-errors=ddl_exist_errors
[mysqld]
gtid_mode=ON #启用gtid类型,不然就是普通的复制架构
log-slave-updates=ON #slave更新是否记入日志
enforce-gtid-consistency=ON #强制GTID的一致性
binlog_format=row #二进制格式改成行row模式
#当设置隔离级别为READ-COMMITED必须设置二进制日志格式为ROW
sync-master-info=1 # 同步主库信息,确保服务器崩溃时无信息丢失
slave-parallel-workers=4 #从服务器的SQL线程数,要复制库数目相同
binlog-checksum=CRC32 # 校验码
master-verify-checksum=1 # 主服校验
slave-sql-verify-checksum=1 #从服校验
binlog-rows-query-log_events=1 # 二进制日志详细记录事件
report-port=3306 # 提供复制报告端口
report-host=station20.example.com #提供复制报告主机
#gitd
gtid_mode = on
enforce_gtid_consistency = 1
transaction-isolation=READ-COMMITTED
binlog_format=row
log_bin=/data/mysqldata/3306/binlog/mysql-bin
log_slave_updates=ON
--5.7 并行复制
# slave
slave-parallel-type=LOGICAL_CLOCK
slave-parallel-workers=16
master_info_repository=TABLE
relay_log_info_repository=TABLE
relay_log_recovery=ON
mysql> show tables like 'replication%';
+---------------------------------------------+
| Tables_in_performance_schema (replication%) |
+---------------------------------------------+
| replication_applier_configuration |
| replication_applier_status |
| replication_applier_status_by_coordinator |
| replication_applier_status_by_worker |
| replication_connection_configuration |
| replication_connection_status |
| replication_group_member_stats |
| replication_group_members |
并行复制配置与调优
master_info_repository 开启MTS功能后,务必将参数master_info_repostitory设置为TABLE
slave_parallel_workers 若将slave_parallel_workers设置为0,则MySQL 5.7退化为原单线程复制,将slave_parallel_workers设置为1
,则SQL线程功能转化为coordinator线程,可是只有1个worker线程进行回放,也是单线程复制。然而,这两种性能却又有一些的区别,由于多了
一次coordinator线程的转发,所以slave_parallel_workers=1的性能反而比0还要差
这里其中引入了另外一个问题,若是主机上的负载不大,那么组提交的效率就不高,颇有可能发生每组提交的事务数量仅有1个,那么在从机
的回放时,虽然开启了并行复制,但会出现性能反而比原先的单线程还要差的现象,即延迟反而增大了
建立函数
log_bin_trust_function_creators=1;
A setting of 0 also enforces the restriction that a function must be declared with the DETERMINISTIC characteristic, or with the READS SQL DATA or NO SQL characteristic.
mysql> SHOW SLAVE STATUS\G
SQL_Delay: 0
SQL_Remaining_Delay: NULL
Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
SET GLOBAL sql_mode = 'modes';
SET SESSION sql_mode = 'modes';
1(SRV_FORCE_IGNORE_CORRUPT):忽略检查到的corrupt页。
2(SRV_FORCE_NO_BACKGROUND):阻止主线程的运行,如主线程须要执行full purge操做,会致使crash。
3(SRV_FORCE_NO_TRX_UNDO):不执行事务回滚操做。
4(SRV_FORCE_NO_IBUF_MERGE):不执行插入缓冲的合并操做。
5(SRV_FORCE_NO_UNDO_LOG_SCAN):不查看重作日志,InnoDB存储引擎会将未提交的事务视为已提交。
6(SRV_FORCE_NO_LOG_REDO):不执行前滚的操做。
innodb_force_recovery default 0
1 (SRV_FORCE_IGNORE_CORRUPT)
Lets the server run even if it detects a corrupt page. Tries to make SELECT * FROM tbl_name jump over corrupt index records and pages, which helps in dumping tables.
2 (SRV_FORCE_NO_BACKGROUND)
Prevents the master thread and any purge threads from running. If a crash would occur during the purge operation, this recovery value prevents it.
3 (SRV_FORCE_NO_TRX_UNDO)
Does not run transaction rollbacks after crash recovery.
4 (SRV_FORCE_NO_IBUF_MERGE)
Prevents insert buffer merge operations. If they would cause a crash, does not do them. Does not calculate table statistics.
This value can permanently corrupt data files. After using this value, be prepared to drop and recreate all secondary indexes.
As of MySQL 5.6.15, sets InnoDB to read-only.
5 (SRV_FORCE_NO_UNDO_LOG_SCAN)
Does not look at undo logs when starting the database: InnoDB treats even incomplete transactions as committed.
This value can permanently corrupt data files. As of MySQL 5.6.15, sets InnoDB to read-only.
6 (SRV_FORCE_NO_LOG_REDO)
Does not do the redo log roll-forward in connection with recovery. This value can permanently corrupt data files.
Leaves database pages in an obsolete state, which in turn may introduce more corruption into B-trees and other database structures. As of MySQL 5.6.15, sets InnoDB to read-only.
innodb_purge_threads Dynamic No
Permitted Values (>= 5.6.5),Default 1
The number of background threads devoted to the InnoDB purge operation.
Default Value (>= 5.7.8) 4
innodb_additional_mem_pool_size 所设置的是用于存放 Innodb 的字典信息和其余一些内部结构所 须要的内存空间
InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
innodb_use_sys_malloc
Default ON
设置为0:表示Innodb使用自带的内存分配程序,设置为1:表示InnoDB使用操做系统的内存分配程序
Whether InnoDB uses the operating system memory allocator (ON) or its own (OFF). The default value is ON. See Section 14.6.4, “Configuring the Memory Allocator for InnoDB” for more information.
innodb_open_files InnoDB一次能够保持打开的.ibd文件的最大数目(
>= 5.6.6 Max Value 4294967295 Default -1 (autosized)
<= 5.6.5 Default 300
thread_stack 64-bit platforms Default 262144,256KB for 64-bit systems
The stack size for each thread. Many of the limits detected by the crash-me test are dependent on this value.
thread_cache_size
How many threads the server should cache for reuse. When a client disconnects,
the client's threads are put in the cache if there are fewer than thread_cache_size threads there.
This variable can be increased to improve performance if you have a lot of new connections.
show status like 'Opened_files';--当前打开表的数量
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Opened_files | 180 |
| table_definition_cache | 1400 |
| table_open_cache | 2000 |
| table_open_cache_instances | 1
一个是打开表的缓存 ---> table_open_cache,每打开一个表,都会读入该值中,当mysql在缓存中找不到,才会读取磁盘
一个是表定义的缓存 ---> table_definition_cache
mysql> show variables like 'open%';
mysql> show variables like 'thread%';
每当客户端链接到mysql数据库时,mysql会建立一个线程为他服务,可是mysql首先回去thread_cache中去找,找不到才会建立新的线程
mysql> show variables like 'thread%';
+--------------------+---------------------------+
| Variable_name | Value |
+--------------------+---------------------------+
| thread_cache_size | 28 |
| thread_concurrency | 10 |
| thread_handling | one-thread-per-connection |
| thread_stack | 262144
slow_launch_time
log_warnings
Permitted Values (64-bit platforms) Default 1
Whether to produce additional warning messages to the error log,This variable is enabled (1) by default and can be disabled by setting it to 0,
log_slow_admin_statements
NO_AUTO_CREATE_USER
NO_ZERO_DATE
NO_ZERO_IN_DATE
ERROR_FOR_DIVISION_BY_ZERO
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER
(system@127.0.0.1:3306) [test]> show variables like 'sql_mode';
+---------------+------------------------------------------------------------------------------------------------------------------------+
| Variable_name | Value |
+---------------+------------------------------------------------------------------------------------------------------------------------+
| sql_mode | STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+---------------+------------------------------------------------------------------------------------------------------------------------+
(system@127.0.0.1:3306) [(none)]> show variables like 'sql_mode'; ##5.6.6 default
+---------------+------------------------+
| Variable_name | Value |
+---------------+------------------------+
| sql_mode | NO_ENGINE_SUBSTITUTION |
+---------------+------------------------+
Default Value (>= 5.7.8) ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ZERO_IN_DATE NO_ZERO_DATE ERROR_FOR_DIVISION_BY_ZERO NO_AUTO_CREATE_USER NO_ENGINE_SUBSTITUTION
mysql常见启动错误----my.cnf中关于innodb的配置,尽可能用默认值,否则不清楚的就容易搞错
#innodb
innodb_data_file_path=ibdata1:12M:autoextend
innodb_log_file_size=256m
innodb_log_files_in_group=3
innodb_buffer_pool_size=512M
InnoDB: http://dev.mysql.com/doc/refman/5.6/en/forcing-innodb-recovery.html
InnoDB: about forcing recovery.
02:56:13 UTC - mysqld got signal 6 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed,
something is definitely wrong and this may fail.
key_buffer_size=8388608
read_buffer_size=1048576
max_used_connections=0
max_threads=214
thread_count=0
connection_count=0
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 449363 K bytes of memory
Hope that's ok; if not, decrease some variables in the equation.
Thread pointer: 0x0
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 0 thread_stack 0x80000
2016-08-02 19:56:13 11665 [Note] InnoDB: 5.6.13 started; log sequence number 1755215
/usr/local/mysql/bin/mysqld(my_print_stacktrace+0x35)[0x8ad2a5]
/usr/local/mysql/bin/mysqld(handle_fatal_signal+0x40b)[0x62aa7b]
/lib64/libpthread.so.0[0x308860f710]
/lib64/libc.so.6(gsignal+0x35)[0x3088232625]
/lib64/libc.so.6(abort+0x175)[0x3088233e05]
/usr/local/mysql/bin/mysqld[0x97b092]
/usr/local/mysql/bin/mysqld[0x97bd2e]
/usr/local/mysql/bin/mysqld[0x97c503]
/usr/local/mysql/bin/mysqld[0x96e1fa]
/lib64/libpthread.so.0[0x30886079d1]
/lib64/libc.so.6(clone+0x6d)[0x30882e89dd]
The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
160802 19:56:14 mysqld_safe mysqld from pid file /data/mysqldata/3306/mysql.pid ended
2016-08-02 20:13:51 12831 [Note] InnoDB: 5.6.13 started; log sequence number 1755215
2016-08-02 20:13:51 12831 [Note] InnoDB: !!! innodb_force_recovery is set to 1 !!!
-------------
innodb_force_recovery=6
innodb_purge_threads=0
./mysqldump_full_bk_yhq.sh
/usr/local/mysql/scripts/mysql_install_db --datadir=/data/mysqldata/3306/data --basedir=/usr/local/mysql
mysqld_safe --defaults-file=/data/mysqldata/3306/my.cnf &
mysql -S /data/mysqldata/3306/mysql.sock<20160802-2025.sql
---
160803 00:45:35 mysqld_safe Number of processes running now: 0
160803 00:45:35 mysqld_safe mysqld restarted
2016-08-03 00:45:47 16581 [Warning] Buffered warning: Could not increase number of max_open_files to more than 1024 (request: 65536)
2016-08-03 00:45:47 16581 [Warning] Buffered warning: Changed limits: max_connections: 214 (requested 4500)
2016-08-03 00:45:47 16581 [Warning] Buffered warning: Changed limits: table_cache: 400 (requested 2000)
2016-08-03 00:45:47 16581 [Warning] Using unique option prefix innodb_read_ahead instead of innodb-read-ahead-threshold is deprecated and will be removed in a future release. Please use the full name instead.
table_cache * 2 + max_connections=max_open_files
ls -lh /proc/16581/fd|wc -l
2016-08-03 02:02:32 17791 [Warning] 'proxies_priv' entry '@ root@hongquan.mysql2' ignored in --skip-name-resolve mode.
mysql> show variables like '%open_files_limit%';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| open_files_limit | 1024 |
[root@hongquan soft]# ulimit -n
1024
mysql> show variables like '%max_connections%';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 214 |
mysql> show variables like '%table_open_cache%';
+----------------------------+-------+
| Variable_name | Value |
+----------------------------+-------+
| table_open_cache | 400 |
| table_open_cache_instances | 1 |
[root@hongquan soft]# vim /etc/security/limits.conf
mysql soft nproc 65535
mysql hard nproc 65535
mysql soft nofile 65535
mysql hard nofile 65535
[root@hongquan soft]# source /etc/profile
[mysql@hongquan 3306]$ ulimit -a
2016-08-03 02:01:58 16581 [Note] Giving 1 client threads a chance to die gracefully
2016-08-03 02:01:58 16581 [Note] Event Scheduler: Purging the queue. 0 events
2016-08-03 02:01:58 16581 [Note] Shutting down slave threads
2016-08-03 02:02:00 16581 [Note] Forcefully disconnecting 1 remaining clients
2016-08-03 02:02:00 16581 [Warning] /usr/local/mysql/bin/mysqld: Forcing close of thread 3 user: 'system'
2016-08-03 02:02:00 16581 [Note] Binlog end
160803 23:32:32 mysqld_safe Starting mysqld daemon with databases from /data/mysqldata/3306/data
2016-08-03 23:32:42 3414 [Warning] Buffered warning: Could not increase number of max_open_files to more than 65535 (request: 65536)
2016-08-03 23:32:42 3414 [Warning] Buffered warning: Performance schema disabled (reason: init failed).
--http://bugs.mysql.com/bug.php?id=72719
2016-08-03 23:32:42 7f74a8a11720 InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
--#innodb_additional_mem_pool_size
016-08-03 23:32:42 3414 [Note] InnoDB: Initializing buffer pool, size = 512.0M
InnoDB: mmap(549453824 bytes) failed; errno 12
2016-08-03 23:32:42 3414 [ERROR] InnoDB: Cannot allocate memory for the buffer pool
2016-08-03 23:32:42 3414 [ERROR] Plugin 'InnoDB' init function returned error.
2016-08-03 23:32:42 3414 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2016-08-03 23:32:42 3414 [ERROR] Unknown/unsupported storage engine: INNODB
2016-08-03 23:32:42 3414 [ERROR] Aborting
innodb_buffer_pool_size=512M
innodb_use_sys_malloc=0
2016-08-03 23:59:30 6677 [Warning] Buffered warning: Performance schema disabled (reason: init failed).
2016-08-03 23:59:31 6677 [Note] Plugin 'FEDERATED' is disabled.
2016-08-03 23:59:31 7f63be3a9720 InnoDB: Warning: Setting innodb_use_sys_malloc to FALSE is DEPRECATED. This option may be removed in future releases, together with the InnoDB's internal memory allocator.
--#innodb_use_sys_malloc=0
2016-08-04 00:05:52 8837 [Warning] Buffered warning: Performance schema disabled (reason: init failed).
2016-08-04 00:05:52 8837 [Note] Plugin 'FEDERATED' is disabled.
2016-08-04 00:05:52 8837 [Note] InnoDB: The InnoDB memory heap is disabled
2016-08-04 00:05:52 8837 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2016-08-04 00:05:52 8837 [Note] InnoDB: Compressed tables use zlib 1.2.3
2016-08-04 00:05:52 8837 [Note] InnoDB: Using CPU crc32 instructions
2016-08-04 00:05:52 8837 [Note] InnoDB: Initializing buffer pool, size = 256.0M
InnoDB: mmap(274726912 bytes) failed; errno 12
2016-08-04 00:05:52 8837 [ERROR] InnoDB: Cannot allocate memory for the buffer pool
2016-08-04 00:05:52 8837 [ERROR] Plugin 'InnoDB' init function returned error.
2016-08-04 00:05:52 8837 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2016-08-04 00:05:52 8837 [ERROR] Unknown/unsupported storage engine: INNODB
2016-08-04 00:05:52 8837 [ERROR] Aborting
max_connections=2000
max_user_connections=1500
mysql> show variables like '%cache%';
注释掉参数
#table_definition_cache=65535
#table_cache=65536
| table_definition_cache | 1400 |
| table_open_cache | 2000 |
| table_open_cache_instances | 1
2016-08-04 00:21:45 9931 [Note] /usr/local/mysql/bin/mysqld: ready for connections.
Version: '5.6.13-r5436-log' socket: '/data/mysqldata/3306/mysql.sock' port: 3306 Source distribution
160804 20:49:29 mysqld_safe Number of processes running now: 0
160804 20:49:29 mysqld_safe mysqld restarted
2016-08-04 20:49:39 16897 [Note] Plugin 'FEDERATED' is disabled.
InnoDB: Doing recovery: scanned up to log sequence number 620450816
160804 21:36:39 mysqld_safe mysqld from pid file /data/mysqldata/3306/mysql.pid ended
innodb_force_recovery=6
2016-08-04 22:50:15 7568 [Note] InnoDB: Highest supported file format is Barracuda.
2016-08-04 22:50:15 7568 [Note] InnoDB: The user has set SRV_FORCE_NO_LOG_REDO on, skipping log redo
2016-08-04 22:50:15 7568 [Note] InnoDB: 5.6.13 started; log sequence number 0
2016-08-04 22:50:15 7568 [Note] InnoDB: !!! innodb_force_recovery is set to 6 !!!
2016-08-04 22:50:16 7568 [Note] Recovering after a crash using /data/mysqldata/3306/binlog/mysql-bin
2016-08-04 22:50:16 7568 [Note] Starting crash recovery...
2016-08-04 22:50:16 7568 [Note] Crash recovery finished.
2016-08-04 22:50:17 7568 [Note] Server hostname (bind-address): '*'; port: 3306
2016-08-04 22:50:17 7568 [Note] IPv6 is available.
2016-08-04 22:50:17 7568 [Note] - '::' resolves to '::';
2016-08-04 22:50:17 7568 [Note] Server socket created on IP: '::'.
2016-08-04 22:50:17 7568 [Warning] 'proxies_priv' entry '@ root@hongquan.mysql2' ignored in --skip-name-resolve mode.
2016-08-04 22:50:17 7568 [ERROR] InnoDB: Failed to find tablespace for table '"mysql"."slave_master_info"' in the cache. Attempting to load the tablespace with space id 8.
2016-08-04 22:50:17 7568 [Warning] InnoDB: Allocated tablespace 8, old maximum was 0
2016-08-04 22:50:17 7568 [ERROR] InnoDB: Failed to find tablespace for table '"mysql"."slave_worker_info"' in the cache. Attempting to load the tablespace with space id 10.
2016-08-04 22:50:17 7568 [ERROR] InnoDB: Failed to find tablespace for table '"mysql"."slave_relay_log_info"' in the cache. Attempting to load the tablespace with space id 9.
2016-08-04 22:50:18 7568 [Note] Event Scheduler: Loaded 0 events
2016-08-04 22:50:18 7568 [Note] /usr/local/mysql/bin/mysqld: ready for connections.
Trying to get some variables.
Some pointers may be invalid and cause the dump to abort.
Query (7f61cc005000): SELECT /*!40001 SQL_NO_CACHE */ * FROM `sbtest1`
Connection ID (thread ID): 1
Status: NOT_KILLED
The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
[ERROR] InnoDB: Failed to find tablespace for table '"sbtest"."sbtest1"' in the cache. Attempting to load the tablespace with space id 27.
ERROR 1010 (HY000): Error dropping database (can't rmdir './sbtest', errno: 39)
Solution :
a. Stopped the mysql service
b. remove the mysql database folder in data directory
c. restart the mysqld service
Note : innodb_file_per_table would help to create each table entry has separate innodb file and this may very useful if the table may have GB of data.
---
[root@hongquan 3306]# tail -f -n 200 slow_query.log
/usr/local/mysql/bin/mysqld, Version: 5.6.13-log (hq for mysql). started with:
Tcp port: 3306 Unix socket: /data/mysqldata/3306/mysql.sock
-----------mysql 5.7
1 认证插件
mysql.user表中的plugin更改为not null,5.7开始再也不支持mysql_old_password的认证插件,推荐所有使用mysql_native_password。从低版本升级到5.7的时候,须要处理两个兼容性问题
[兼容性]
须要先迁移mysql_old_password的用户,而后进行user表结构的升级
1. 迁移mysql_old_password用户
MySQL 5.7.2以前的版本,是根据password的hash value来判断使用的认证插件类型,5.7.2之后的版本,plugin字段为not null,就直接根据plugin来判断了。新的密码从password字段中,保存到新的字段authentication_string中,password字段废弃处理
若是user是隐式的mysql_native_password。直接使用sql进行变动:
UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE plugin = '' AND (Password = '' OR LENGTH(Password) = 41);
FLUSH PRIVILEGES;
若是user是隐式的或者显示的mysql_old_password, 首先经过如下sql进行查询
SELECT User, Host, Password FROM mysql.user WHERE (plugin = '' AND LENGTH(Password) = 16) OR plugin = 'mysql_old_password';
若是存在记录,就表示还有使用mysql_old_password的user,使用如下sql进行用户的迁移
ALTER USER 'user1'@'localhost' IDENTIFIED WITH mysql_native_password BY 'DBA-chosen-password';
user表结构升级
经过mysql_upgrade直接进行升级,步骤以下[5.6->5.7]:
stop MySQL 5.6实例
替换5.7的mysqld二进制版本
使用5.7启动实例
run mysql_upgrade升级系统表
重启MySQL 5.7实例
2 密码过时
用户能够经过 ALTER USER 'jeffrey'@'localhost' PASSWORD EXPIRE;这样的语句来使用户的密码过时。
并新增长 default_password_lifetime来表示用户密码自动过时时间,从5.7.10开始,其默认值从0变动到了360,也就是默认一年过时
能够经过如下两种方法禁止过时:
SET GLOBAL default_password_lifetime = 0;
ALTER USER 'jeffrey'@'localhost' PASSWORD EXPIRE NEVER;
[兼容性]
只须要经过mysql_upgrade升级mysql.user系统表就可使用密码过时新功能
(system@127.0.0.1:3306) [(none)]> show variables like '%password%';
3 帐号锁定
用户能够经过如下语法进行帐号锁定,阻止这个用户进行登陆:
ALTER USER 'jeffrey'@'localhost' ACCOUNT LOCK;
ALTER USER 'jeffrey'@'localhost' ACCOUNT UNLOCK;
4 SSL链接
若是mysqld编译使用的openssl,在启动的时候,默认建立SSL, RSA certificate 和 key 文件。
但无论是openssl仍是yassl,若是没有设置ssl相关的参数,mysqld都会在data directory里查找ssl认证文件,来尽可能打开ssl特性。
(system@127.0.0.1:3306) [(none)]> show global variables like '%ssl%';
5 安装数据库
5.7开始建议用户使用 mysqld --initialize来初始化数据库,放弃以前的mysql_install_db的方式,新的方式只建立了一个root@localhost的用户,
随机密码保存在~/.mysql_secret文件中,而且帐号是expired,第一次使用必须reset password,而且再也不建立test db。
6 sql mode变动
mode_no_engine_substitution |
mode_only_full_group_by |
mode_strict_trans_tables |
mode_no_zero_in_date |
mode_no_zero_date |
mode_error_for_division_by_zero |
mode_no_auto_create_user
7 online alter table
支持online rename index操做, in_place而且不须要table copy。
8 InnoDB加强
变动varchar 类型字段的长度支持inplace方法,但有一个限制,即用于表示varchar字段长度的字节数不能发生变化,也就是支持好比varchar的
长度在255如下变动或者255以上的范围进行变动,由于从小于255变动到大于255,其size的字节须要从1个增长到2个。
注意:减小varchar的长度,仍然须要table copy
9 优化InnoDB临时表
由于InnoDB临时表的数据再也不不受redo保护,而redo只保护临时表的元数据,因此大幅提高了临时表的性能。
而且InnoDB临时表的元数据保存在一个新的系统表中即innodb_temp_table_info,
临时表将创建一个统一的表空间,咱们称之为临时表空间,其目录地址能够经过参数innodb_temp_data_file_path来设置。系统在启动的时候,都会新建这个表空间,重启会删除重建。
(system@127.0.0.1:3306) [(none)]> show global variables like '%temp%';
+----------------------------+-----------------------+
| Variable_name | Value |
+----------------------------+-----------------------+
| avoid_temporal_upgrade | OFF |
| innodb_temp_data_file_path | ibtmp1:12M:autoextend |
| show_old_temporals | OFF |
+----------------------------+-----------------------+
(system@127.0.0.1:3306) [(none)]> show global variables like '%storage_engine%';
注意: 在开启gtid的状况下,非auto commit或者显示begin的context下,create 或者drop 临时表,仍然和5.6同样
ERROR 1787 (HY000): Statement violates GTID consistency: CREATE TEMPORARY TABLE and DROP TEMPORARY TABLE can only be executed outside transactional context.
另外, insert into t select * from t也会遇到错误,不能在一个sql语句中reference两次临时表
在5.7中,咱们将临时表从数据字典中分离出来,这样,临时表就不会跟其余正常表争抢数据字典的锁。同时,咱们还将临时表的表空间跟普通表空间区别开来,以减小IO的开销
对于临时表的DML操做,咱们只记录Undo日志,不记录Redo日志,由于,临时表不须要在Crash的时候Recovery,可是它须要rollback。这样也减小了大量的日志开销
10 InnoDB原生支持DATA_GEOMETRY类型
而且支持在spatial data types上创建index,加速查询
CREATE TABLE triangle (sidea int, sideb int, area DOUBLE AS (sidea * sideb / 2),sumab int as (sidea + sideb));
insert into triangle(sidea, sideb) values(3, 4);
select * from triangle;
11 buffer pool dump
buffer pool dump和load支持一个新的参数innodb_buffer_pool_dump_pct,即dump的比例,而且使用innodb_io_capacity 来控制load过程当中的IO吞吐量
12 多线程flush dirty
从5.7.4开始,innodb_page_cleaners参数能够设置,支持多线程flush dirty page,加快脏块的刷新
innodb-page-cleaners = 8
performance-schema = OFF
13 NVM file system
MySQL 一直使用double write buffer来解决一个page写入的partial write问题,但在linux系统上的Fusion-io Non-Volatile Memory (NVM) file system支持原子的写入。
这样就能够省略掉double write buffer的使用, 5.7.4之后,若是Fusion-io devices支持atomic write,那么MySQL自动把dirty block直接写入到数据文件了。这样减小了一次内存copy和IO操做。
14 InnoDB分区表
MySQL 5.7以前的版本,InnoDB并不支持分区表,分区表的支持是在ha_partition引擎上支持的,从5.7开始,InnoDB支持原生的分区表,而且可使用传输表空间
[兼容性]
mysql_upgrade会扫描ha_partition引擎支持的InnoDB表,并升级成InnoDB分区表,5.7.9以后,能够经过命令ALTER TABLE … UPGRADE PARTITIONING.进行升级。
若是以前的版本大量使用了分区表,要注意使用mysql_upgrade会消耗很是长的时间来升级分区表
15 动态调整buffer pool size
MySQL 5.7.5以后,能够online动态调整buffer pool size,经过设置动态的参数innodb_buffer_pool_size来调整,而且根据Innodb_buffer_pool_resize_status状态来
查看resize的进度,由于resize的过程是以chunk为大小,把pages从一个内存区域copy到另外一片内存的
innodb_buffer_pool_size can be configured dynamically, while the server is running.
16 加快recovery
MySQL 5.7.5以前,在recovery的过程当中,须要扫描全部的ibd文件,获取元信息, 5.7.5以后,新加了一种redo log类型,即MLOG_FILE_NAME,
记录从上一次checkpoint以来,发生过变动的文件,这样在recovery的过程当中,只须要打开这些文件就能够了。
[兼容性]
由于增长了新的log record type,须要安全的关闭5.7以前的实例,清理掉redo。
17 表空间管理
支持建立表空间,例如
CREATE TABLESPACE `tablespace_name`
ADD DATAFILE 'file_name.ibd'
[FILE_BLOCK_SIZE = n]
并能够在建立表的时候,指定属于哪一个表空间,
[兼容性]
由于能够任意指定空间目录,要注意升级过程当中,不要漏掉目录。
18 InnoDB Tablespace Encryption
支持InnoDB数据文件加密,其依赖keyring plugin来进行秘钥的管理,后面咱们单独来介绍InnoDB加密的方法,而且RDS也实现了一种InnoDB数据文件透明加密方法,并经过KMS系统来管理秘钥。例如:
create table t(id int) encryption='y';
SELECT PLUGIN_NAME, PLUGIN_STATUS FROM INFORMATION_SCHEMA.PLUGINS WHERE PLUGIN_NAME LIKE 'keyring%';
19 事务相关优化
对InnoDB的事务(transaction)进行了优化,建立事务池(Transaction Pool),这样就能减小不少事务建立和释放的开销
优化了事务的生命周期管理。全部事务首先都默认为是只读事务,这样这些事务就不会和其余事务冲突,只有当此事务开始一个写操做时才认为它是一个读写事务:
20 支持更大的数据页
以前咱们支持的是4k,8k,16k,如今能够支持32k,64k了。这样一些blob数据就能够直接存在页里,访问起来更快
21 GIS的支持
在5.7中最重要的新功能是对GIS的支持。咱们在InnoDB内部实现了基于R-tree的空间索引,这样用户就能很方便的查找地理信息数据了
好比,查找以我为中心,周围2千米范围内的妹子之类的操做将变得异常迅速,
innodb undo log
(system@127.0.0.1:3306) [test]> show variables like '%undo%';
+--------------------------+------------+
| Variable_name | Value |
+--------------------------+------------+
| innodb_max_undo_log_size | 1073741824 |--达到最大值开始进行收缩
| innodb_undo_directory | ./ |--存放目录
| innodb_undo_log_truncate | OFF |--在线开启undo log回收
| innodb_undo_logs | 128 |--指定回滚段
| innodb_undo_tablespaces | 0 |--undo log 文件 >=2
+--------------------------+------------+
explicit_defaults_for_timestamp=1 default off
默认关闭,容许服务器使用非标准的TIMESTAMP columns
malloc-lib=tcmalloc
--malloc-lib Alternative malloc library to use for mysqld
If the option is given as --malloc-lib=tcmalloc, mysqld_safe looks for a tcmalloc library
in /usr/lib and then in the MySQL pkglibdir location (for example, /usr/local/mysql/
lib or whatever is appropriate). If tmalloc is found, its path name is added to the beginning of
the LD_PRELOAD value for mysqld. If tcmalloc is not found, mysqld_safe aborts with an error.
If the option is given as --malloc-lib=/path/to/some/library, that full path is added to
the beginning of the LD_PRELOAD value. If the full path points to a nonexistent or unreadable file,
mysqld_safe aborts with an error.
loose_innodb_numa_interleave = 1
MySQL 5.7 InnoDB提供了新的参数innodb_numa_interleave,即缓冲池内存的分配策略采用interleave的方式
innodb_numa_interleave 5.6.27
Default Value OFF
Enables the NUMA interleave memory policy for allocation of the InnoDB buffer pool. When
innodb_numa_interleave is enabled, the NUMA memory policy is set to MPOL_INTERLEAVE for
the mysqld process. After the InnoDB buffer pool is allocated, the NUMA memory policy is set back to
MPOL_DEFAULT. For the innodb_numa_interleave option to be available, MySQL must be compiled
on a NUMA-enabled Linux system.
binlog_gtid_simple_recovery
5.7.6如下中默认
simplified_binlog_gtid_recovery=flase
可是这会致使过多的BINLOG扫描,何况5.6没有mysql.gtid_executed的支持,从库必须开启log_slave_updates,这会带来性能影响。因此仍是少用GTID。
5.7.6以上中默认
binlog_gtid_simple_recovery=true
5.7.6以上因为对每一个BINLOG都有Previous gtid Event的支持binlog_gtid_simple_recovery=true是合理的设置,BINLOG扫描很是的快由于只是第一个和最后一个BINLOG文件而已。
能够看到Gtid也愈来愈成熟了。
(system@127.0.0.1:3306) [test]> show variables like '%gtid%';
+----------------------------------+-------------------------------------------------+
| Variable_name | Value |
+----------------------------------+-------------------------------------------------+
| binlog_gtid_simple_recovery | ON |
| enforce_gtid_consistency | ON |
| gtid_executed_compression_period | 1000 |
| gtid_mode | ON |
| gtid_next | AUTOMATIC |
| gtid_owned | |
| gtid_purged | 3d8c27f0-ff21-11e7-9564-0800279374ba:1-15862163 |
| session_track_gtids | OFF |
+----------------------------------+-------------------------------------------------+
show_compatibility_56 = on
--从mysql5.7.6开始information_schema.global_status已经开始被舍弃,为了兼容性,此时须要打开 show_compatibility_56
(system@127.0.0.1:3306) [test]> select * from information_schema.global_status limit 3;
ERROR 3167 (HY000): The 'INFORMATION_SCHEMA.GLOBAL_STATUS' feature is disabled; see the documentation for 'show_compatibility_56'
(system@127.0.0.1:3306) [test]> show variables like '%show_compatibility_56%';
+-----------------------+-------+
| Variable_name | Value |
+-----------------------+-------+
| show_compatibility_56 | OFF |
--把show_compatibility_56打开
mysql> set global show_compatibility_56=on;
validate_password=OFF 5.7 中可关闭密码检测插件
# password plugin #
validate_password_policy = STRONG
validate-password = FORCE_PLUS_PERMANENT
validate_password_policy=默认是1 :符合长度,且必须含有数字,小写或大写字母,特殊字符
0 or LOW
Length
1 or MEDIUM
Length; numeric, lowercase/uppercase, and special characters
2 or STRONG
Length; numeric, lowercase/uppercase, and special characters; dictionary file
安装validate_password插件:
install plugin valaidte_password soname 'validate_password.so';
log_error_verbosity = 2
Default Value 3
Desired Log Filtering log_error_verbosity Value
Error messages 1
Error and warning messages 2
Error, warning, and note messages 3
min_examined_row_limit 查询检查返回少于该参数指定行的SQL不被记录到慢查询日志
--
slave_skip_errors
--slave-skip-errors=[err_code1,err_code2,...|all|ddl_exist_errors]
System Variable slave_skip_errors
Dynamic No
Default Value OFF
Valid Values OFF [list of error codes] all /ddl_exist_errors
The shorthand value ddl_exist_errors is equivalent to the error code list 1007,1008,1050,1051,1054,1060,1061,1068,1094,1146.
--slave-skip-errors=1062,1053
--slave-skip-errors=all
--slave-skip-errors=ddl_exist_errors
slave-skip-errors=1032
optimizer_search_depth
这个参数控制优化器在穷举执行计划时的限度。若是查询长时间处于"statistics"状态,能够考虑调低此参数
optimizer_prune_level
默认是打开的,这让优化器会根据须要扫描的行数来决定是否跳过某些执行计划
optimizer_switch
这个变量包含了一些开启/关闭优化器特性的标志位
set optimizer_switch='mrr=on,mrr_cost_based=off,batched_key_access=on';
set optimizer_switch='mrr_cost_based=off';
innodb_strict_mode
Default Value (>= 5.7.7) ON
Oracle recommends enabling innodb_strict_mode when specifying KEY_BLOCK_SIZE for
InnoDB tables. When innodb_strict_mode is enabled, specifying an invalid KEY_BLOCK_SIZE
value returns an error. If innodb_strict_mode is disabled, an invalid KEY_BLOCK_SIZE value
results in a warning, and the KEY_BLOCK_SIZE option is ignored.
innodb_write_io_threads = 16
innodb_read_io_threads = 16 The number of I/O threads for read operations in InnoDB.
Default Value 4
event_scheduler 事件是否开启
event_scheduler = 1
(system@127.0.0.1:3306) [trunk]> show variables like '%performance_sch%';
+----------------------------------------------------------+-------+
| Variable_name | Value |
+----------------------------------------------------------+-------+
| performance_schema | ON |
(system@127.0.0.1:3306) [trunk]> show variables like '%instance%';
+------------------------------------------------------+-------+
| Variable_name | Value |
+------------------------------------------------------+-------+
| innodb_buffer_pool_instances | 2 |
| metadata_locks_hash_instances | 8 |
| table_open_cache_instances | 16 |
table_open_cache_instances 指的是 MySQL 缓存 table 句柄的分区的个数,而每个 cache_instance 能够包含不超过table_open_cache/table_open_cache_instances 的table_cache_element
MySQL 打开表的过程能够简单的归纳为:
1根据线程的 thread_id 肯定线程将要使用的 table_cache,即 thread_id % table_cache_instances;
2从该 tabel_cache 元素中查找相关系连的 table_cache_element,若是存在转 3,若是不存在转 4;
3从 2 中查找的table_cache_element 的 free_tables 中出取一个并返回,并调整 table_cache_element 中的 free_tables & used_tables 元素;
4若是 2 中不存在,则从新建立一个 table, 并加入对应的 table_cache_element 的 used_tables的列表;
从以上过程能够看出,MySQL 在打开表的过程当中会首先从 table_cache 中进行查找有没有能够直接使用的表句柄,有则直接使用
没有则会建立并加入到对应的 table_cache 中对应的 table_cache_element 中
performance schema 是 MySQL 的内部诊断器,用于记录 MySQL 在运行期间的各类信息,如表锁状况、mutex 竟争状况、执行语句的状况等,和
Information Schema 相似的是拥用的信息都是内存信息,而不是存在磁盘上的,但和 information_schema 有如下不一样点:
information_schema 中的信息都是从 MySQL 的内存对象中读出来的,只有在须要的时候才会读取这些信息,如 processlist, profile, innodb_trx 等,
不须要额外的存储或者函数调用,而 performance schema 则是经过一系列的回调函数来将这些信息额外的存储起来,
使用的时候进行显示,所以 performance schema 消耗更多的 CPU & memory 资源;
Information_schema 中的表是没有表定义文件的,表结构是在内存中写死的,而 performation_schema 中的表是有表定义文件的;
实现方式不一样,Information_schema 只是对内存的 traverse copy, 而 performance_schema 则使用固定的接口来进行实现;
做用不一样,Information_schema 主要是轻量级的使用,即便在使用的时候也不多会有性能影响,performance_schema 则是 MySQL 的内部监控系统,能够很好的定位性能问题,但也很影响性能;
table_open_cache_instances=32
metadata_locks_hash_instances=32
performance_schema=OFF
innodb_purge_threads=4
(system@127.0.0.1:3306) [trunk]> show variables like '%spin%';
+------------------------+-------+
| Variable_name | Value |
+------------------------+-------+
| innodb_spin_wait_delay | 6 |
| innodb_sync_spin_loops | 30 |
--character-set-server=charset_name, -C charset_name
Default Value latin1 #5.6,5.7
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
----
[client]
default-character-set = utf8mb4
[mysql]
default-character-set = utf8mb4
[mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
init_connect='SET NAMES utf8mb4'
innodb_buffer_pool_load_at_startup
Default Value (>= 5.7.7) ON
Default Value (<= 5.7.6)
Specifies that, on MySQL server startup, the InnoDB buffer pool is automatically warmed
up by loading the same pages it held at an earlier time. Typically used in combination with
innodb_buffer_pool_dump_at_shutdown
Both innodb_buffer_pool_dump_at_shutdown and
innodb_buffer_pool_load_at_startup are enabled by default
innodb_monitor_enable
SHOW ENGINE PERFORMANCE_SCHEMA STATUS\G
This statement is intended to help the DBA understand the effects that different Performance Schema
options have on memory requirements
table_cache_size 打开表的线程数量
myisam_max_sort_file_size
The maximum size of the temporary file that MySQL is permitted to use while re-creating a MyISAM
index (during REPAIR TABLE, ALTER TABLE, or LOAD DATA INFILE).
-----------mysql 5.6
Table 5.1 Changes to Server Defaults in MySQL 5.6
Parameter Old Default New Default Version
back_log 50 Autosized using max_connections 5.6.6
binlog_checksum NONE CRC32 5.6.6
--binlog-row-event-max-size 1024 8192 5.6.6
flush_time 1800 (on Windows) 0 5.6.6
host_cache_size 128 Autosized using max_connections 5.6.8
innodb_autoextend_increment 8 64 5.6.6
innodb_buffer_pool_instances 1 8 (platform dependent) 5.6.6
innodb_concurrency_tickets 500 5000 5.6.6
innodb_data_file_path ibdata1:10M:autoextend ibdata1:12M:autoextend 5.6.7
innodb_file_per_table 0 1 5.6.6
innodb_log_file_size 5MB 48MB 5.6.8
innodb_old_blocks_time 0 1000 5.6.6
innodb_open_files 300 Autosized using innodb_file_per_table, table_open_cache 5.6.6
innodb_stats_on_metadata ON OFF 5.6.6
join_buffer_size 128KB 256KB 5.6.6
max_allowed_packet 1MB 4MB 5.6.6
max_connect_errors 10 100 5.6.6
open_files_limit 0 Autosized using max_connections 5.6.8
performance_schema OFF ON 5.6.6
performance_schema_events_waits_history_long_size 10000 Autosized 5.6.6
performance_schema_events_waits_history_size 10 Autosized 5.6.6
performance_schema_max_cond_instances 1000 Autosized 5.6.6
performance_schema_max_file_instances 10000 Autosized 5.6.6
performance_schema_max_mutex_instances 1000000 Autosized 5.6.6
performance_schema_max_rwlock_instances 1000000 Autosized 5.6.6
performance_schema_max_table_handles 100000 Autosized 5.6.6
performance_schema_max_table_instances 50000 Autosized 5.6.6
performance_schema_max_thread_instances 1000 Autosized 5.6.6
query_cache_size 0 1M 5.6.8
query_cache_type ON OFF 5.6.8
secure_auth OFF ON 5.6.7
sql_mode '' (empty string) NO_ENGINE_SUBSTITUTION 5.6.6
sync_master_info 0 10000 5.6.6
sync_relay_log 0 10000 5.6.6
sync_relay_log_info 0 10000 5.6.6
table_definition_cache 400 Autosized using table_open_cache 5.6.8
table_open_cache 400 2000 5.6.8
thread_cache_size 0 Autosized using max_connections 5.6.8
--5.6 time_zone
the initial value of this is 'SYSTEM' (which means, “use the value of system_time_zone”)
time_zone默认是system,则用的值就是system_time_zone的值
This variable is used to initialize the time zone for each client that connects.
default 'SYSTEM'
If set to SYSTEM, every MySQL function call that requires a timezone calculation
makes a system library call to determine the current system timezone. This call
may be protected by a global mutex, resulting in contention.
--set global time_zone = '+8:00';
(system@127.0.0.1:3306) [(none)]> set time_zone='+8:00';
Query OK, 0 rows affected (0.00 sec)
(system@127.0.0.1:3306) [(none)]> show variables like '%time_zone%';
+------------------+--------+
| Variable_name | Value |
+------------------+--------+
| system_time_zone | CST |
| time_zone | +08:00 |
+------------------+--------+
(system@127.0.0.1:3306) [(none)]> select now(),CURRENT_TIMESTAMP;
+---------------------+---------------------+
| now() | CURRENT_TIMESTAMP |
+---------------------+---------------------+
| 2018-11-23 14:45:40 | 2018-11-23 14:45:40 |
+---------------------+---------------------+
(system@127.0.0.1:3306) [(none)]> set time_zone='+0:00';
+---------------------+---------------------+
(system@127.0.0.1:3306) [(none)]> select now(),CURRENT_TIMESTAMP;
+---------------------+---------------------+
| now() | CURRENT_TIMESTAMP |
+---------------------+---------------------+
| 2018-11-23 06:46:24 | 2018-11-23 06:46:24 |
+---------------------+---------------------+
发起死锁检测,主动回滚死锁链条中的某一个事务,能够禁用死锁检测,在高并发系统能够提高必定的性能
innodb_deadlock_detect(default=on) (5.7.15以后的参数)
This option is used to disable deadlock detection. On high concurrency systems, deadlock detection
can cause a slowdown when numerous threads wait for the same lock. At times, it may be more
efficient to disable deadlock detection and rely on the innodb_lock_wait_timeout setting for
transaction rollback when a deadlock occurs.
innodb_change_buffer_max_size(system@127.0.0.1:3306) [(none)]> show variables like 'innodb_change%';+-------------------------------+---------+| Variable_name | Value |+-------------------------------+---------+| innodb_change_buffer_max_size | 25 | //change buffer最多占用buffer pool的25%| innodb_change_buffering | inserts |+-------------------------------+---------+