为什么要优化
如何优化
原则:尽量使用整型表示字符串
# INET_ATON(str),address to number # INET_NTOA(number),number to address
enum原则:定长和非定长数据类型的选择
# decimal不会损失精度,存储空间会随数据的增大而增大。double占用固定空间,较大数的存储会损失精度。非定长的还有varchar、text
金额
# 对数据的精度要求较高,小数的运算和存储存在精度问题(不能将所有小数转换成二进制)
# price decimal(8,2)有2位小数的定点数,定点数支持很大的数(甚至是超过int,bigint存储范围的数)
# 定长char,非定长varchar、text(上限65535,其中varchar还会消耗1-3字节记录长度,而text使用额外空间记录长度)
原则:尽可能选择小的数据类型和指定短的长度
null字段的处理要比null字段的处理高效些!且不需要判断是否为null。null在MySQL中,不好处理,存储需要额外空间,运算也需要特殊的运算符。如select null = null和select null <> null(<>为不等号)有着同样的结果,只能通过is null和is not null来判断字段是否为null。null。因此通常使用特殊的数据进行占位,比如int not null default 0、string not null default ‘’原则:字段注释要完整,见名知意
原则:单表字段不宜过多
原则:可以预留字段
# 在使用以上原则之前首先要满足业务需求
# 外键foreign key只能实现一对一或一对多的映射
item)和商品的详细信息(item_intro),通常使用相同的主键或者增加一个外键字段(item_id)
# 数据表的设计规范,一套越来越严格的规范体系(如果需要满足N范式,首先要满足N-1范式)。N
java的文章)第二范式:消除对主键的部分依赖
| course_name | course_class | weekday(周几) | course_teacher | 
|---|---|---|---|
| MySQL | 教育大楼1525 | 周一 | 张三 | 
| Java | 教育大楼1521 | 周三 | 李四 | 
| MySQL | 教育大楼1521 | 周五 | 张三 | 
id作为主键,而消除对主键的部分依赖。第三范式:消除对主键的传递依赖
id。因此需要将此表拆分为两张表日程表和课程表(独立数据独立建表):| id | weekday | course_class | course_id | 
|---|---|---|---|
| 1001 | 周一 | 教育大楼1521 | 3546 | 
| course_id | course_name | course_teacher | 
|---|---|---|
| 3546 | Java | 张三 | 
course_id:3546出现了7次)
# 早期问题:如何选择MyISAM和Innodb? # 现在不存在这个问题了,Innodb不断完善,从各个方面赶超MyISAM,也是MySQL默认使用的。
存储引擎Storage engine:MySQL中的数据、索引以及其他对象是如何存储的,是一套文件系统的实现。
show engines| Engine | Support | Comment | 
|---|---|---|
| InnoDB | DEFAULT | Supports transactions, row-level locking, and foreign keys | 
| MyISAM | YES | MyISAM storage engine | 
| MyISAM | Innodb | |
|---|---|---|
| 文件格式 | 数据和索引是分别存储的,数据 .MYD,索引.MYI | 数据和索引是集中存储的, .ibd | 
| 文件能否移动 | 能,一张表就对应 .frm、MYD、MYI3个文件 | 否,因为关联的还有 data下的其它文件 | 
| 记录存储顺序 | 按记录插入顺序保存 | 按主键大小有序插入 | 
| 空间碎片(删除记录并 flush table 表名之后,表文件大小不变) | 产生。定时整理:使用命令 optimize table 表名实现 | 不产生 | 
| 事务 | 不支持 | 支持 | 
| 外键 | 不支持 | 支持 | 
| 锁支持(锁是避免资源争用的一个机制,MySQL锁对用户几乎是透明的) | 表级锁定 | 行级锁定、表级锁定,锁定力度小并发能力高 | 
锁扩展
table-level lock):lock tables <table_name1>,<table_name2>... read/write,unlock tables <table_name1>,<table_name2>...。其中read是共享锁,一旦锁定任何客户端都不可读;write是独占/写锁,只有加锁的客户端可读可写,其他客户端既不可读也不可写。锁定的是一张表或几张表。row-level lock):锁定的是一行或几行记录。共享锁:select * from <table_name> where <条件> LOCK IN SHARE MODE;,对查询的记录增加共享锁;select * from <table_name> where <条件> FOR UPDATE;,对查询的记录增加排他锁。这里值得注意的是:innodb的行锁,其实是一个子范围锁,依据条件锁定部分范围,而不是就映射到具体的行上,因此还有一个学名:间隙锁。比如select * from stu where id < 20 LOCK IN SHARE MODE会锁定id在20左右以下的范围,你可能无法插入id为18或22的一条新纪录。选择依据
Innodb即可。
索引检索为什么快?
key),唯一索引(unique key),主键索引(primary key),全文索引(fulltext key)索引管理语法
show create table 表名:desc 表名创建索引
create TABLE user_index( id int auto_increment primary key, first_name varchar(16), last_name VARCHAR(16), id_card VARCHAR(18), information text ); # -- 更改表结构 alter table user_index # -- 创建一个first_name和last_name的复合索引,并命名为name add key name (first_name,last_name), # -- 创建一个id_card的唯一索引,默认以字段名作为索引名 add UNIQUE KEY (id_card), # -- 鸡肋,全文索引不支持中文 add FULLTEXT KEY (information);
show create table user_index:CREATE TABLE user_index2 ( id INT auto_increment PRIMARY KEY, first_name VARCHAR (16), last_name VARCHAR (16), id_card VARCHAR (18), information text, KEY name (first_name, last_name), FULLTEXT KEY (information), UNIQUE KEY (id_card) );
alter table 表名 drop KEY 索引名alter table user_index drop KEY name;
alter table user_index drop KEY id_card;
alter table user_index drop KEY information; 
alter table 表名 drop primary key(因为主键只有一个)。这里值得注意的是,如果主键自增长,那么不能直接执行此操作(自增长依赖于主键索引):alter table user_index # -- 重新定义字段 MODIFY id int, drop PRIMARY KEY
执行计划explain
CREATE TABLE innodb1 ( id INT auto_increment PRIMARY KEY, first_name VARCHAR (16), last_name VARCHAR (16), id_card VARCHAR (18), information text, KEY name (first_name, last_name), FULLTEXT KEY (information), UNIQUE KEY (id_card) ); insert into innodb1 (first_name,last_name,id_card,information) values (‘张‘,‘三‘,‘1001‘,‘华山派‘);
explain selelct来分析SQL语句执行前的执行计划:索引使用场景(重点)
where
id查询记录,因为id字段仅建立了主键索引,因此此SQL执行可选的索引只有主键索引,如果有多个,最终会选一个较优的作为检索的依据。# -- 增加一个没有建立索引的字段 alter table innodb1 add sex char(1); # -- 按sex检索时可选的索引为null EXPLAIN SELECT * from innodb1 where sex=‘男‘;
alter table 表名 add index(字段名)),同样的SQL执行的效率,你会发现查询效率会有明显的提升(数据量越大越明显)。order by将查询结果按照某个字段排序时,如果该字段没有建立索引,那么执行计划会将查询出的所有数据使用外部排序(将数据从硬盘分批读取到内存使用内部排序,最后合并排序结果),这个操作是很影响性能的,因为需要将查询涉及到的所有数据从磁盘中读到内存(如果单条数据过大或者数据量过多都会降低效率),更无论读到内存之后的排序了。alter table 表名 add index(字段名),那么由于索引本身是有序的,因此直接按照索引的顺序和映射关系逐条取出数据即可。而且如果分页的,那么只用取出索引表某个范围内的索引对应的数据,而不用像上述那取出所有数据进行排序再返回某个范围内的数据。(从磁盘取数据是最影响性能的)join语句匹配关系(on)涉及的字段建立索引能够提高效率select后==只写必要的查询字段==,以增加索引覆盖的几率。where/order by/join on或索引覆盖),索引也不一定被使用select * from user where id = 20-1; select * from user where id+1 = 20;
like查询,不能以通配符开头
mysql的文章:# select * from article where title like ‘%mysql%‘;
like语句匹配表达式以通配符开头),因此只能做全表扫描,效率极低,在实际工程中几乎不被采用。而一般会使用第三方提供的支持中文的全文索引来做。mysql之后提醒mysql 教程、mysql 下载、mysql 安装步骤等。用到的语句是:# select * from article where title like ‘mysql%‘;
like是可以利用索引的(当然前提是title字段建立过索引)。复合索引只对第一个字段有效
# alter table person add index(first_name,last_name);
first_name中提取的关键字排序,如果无法确定先后再按照从last_name提取的关键字排序,也就是说该索引表只是按照记录的first_name字段值有序。select * from person where first_name = ?是可以利用索引的,而select * from person where last_name = ?无法利用索引。select * person from first_name = ? and last_name = ?,复合索引就比对first_name和last_name单独建立索引要高效些。很好理解,复合索引首先二分查找与first_name = ?匹配的记录,再在这些记录中二分查找与last_name匹配的记录,只涉及到一张索引表。而分别单独建立索引则是在first_name索引表中二分找出与first_name = ?匹配的记录,再在last_name索引表中二分找出与last_name = ?的记录,两者取交集。or,两边条件都有索引可用
状态值,不容易使用到索引
如何创建索引
where、order by、join字段上建立索引。前缀索引
index(field(10)),使用字段值的前10个字符建立索引,默认是使用字段的全部内容建立索引。select count(*)/count(distinct left(password,prefixLen));,通过从调整prefixLen的值(从1自增)查看不同前缀长度的一个平均匹配度,接近1时就可以了(表示一个密码的前prefixLen个字符几乎能确定唯一一条记录)索引的存储结构
BTree
add index(first_name,last_name)为例:first_name第一有序、last_name第二有序的规则,新添加的韩香就可以插到韩康之后。白起 < 韩飞 < 韩康 < 李世民 < 赵奢 < 李寻欢 < 王语嫣 < 杨不悔。这与二叉搜索树的思想是一样的,只不过二叉搜索树的查找效率是log(2,N)(以2为底N的对数),而BTree的查找效率是log(x,N)(其中x为node的关键字数量,可以达到1000以上)。log(1000+,N)可以看出,少量的磁盘读取即可做到大量数据的遍历,这也是btree的设计目的。Innodb的==主键索引为聚簇结构==,其它的索引包括Innodb的非主键索引都是典型的BTree结构。哈希索引
select语句的查询结果在配置文件中开启缓存
my.ini,linux上是my.cnf[mysqld]段中配置query_cache_type:
select sql-no-cache提示来放弃缓存select sql-cache来主动缓存(==常用==)show variables like ‘query_cache_type’;来查看:# show variables like ‘query_cache_type‘; # query_cache_type DEMAND
query_cache_size来设置:# show variables like ‘query_cache_size‘; # query_cache_size 0 # set global query_cache_size=64*1024*1024; # show variables like ‘query_cache_size‘; # query_cache_size 67108864
将查询结果缓存
# select sql_cache * from user;
重置缓存
# reset query cache;
缓存失效问题(大问题)
注意事项
query cache的使用情况。可以尝试使用,但不能由query cache决定业务逻辑,因为query cache由DBA来管理。
MyISAM存储引擎时是一个.MYI和.MYD文件,使用Innodb存储引擎时是一个.ibd和.frm(表结构)文件。id分区,如下将id的哈希值对10取模将数据均匀分散到10个.ibd存储文件中:create table article( id int auto_increment PRIMARY KEY, title varchar(64), content text )PARTITION by HASH(id) PARTITIONS 10
data目录:MySQL提供的分区算法
hash(field)的性质一样,只不过key是==处理字符串==的,比hash()多了一步从字符串中计算出一个整型在做取模操作。create table article_key( id int auto_increment, title varchar(64), content text, PRIMARY KEY (id,title) # -- 要求分区依据字段必须是主键的一部分 )PARTITION by KEY(title) PARTITIONS 10
create table article_range( id int auto_increment, title varchar(64), content text, created_time int, # -- 发布时间到1970-1-1的毫秒数 PRIMARY KEY (id,created_time) # -- 要求分区依据字段必须是主键的一部分 )charset=utf8 PARTITION BY RANGE(created_time)( PARTITION p201808 VALUES less than (1535731199), -- select UNIX_TIMESTAMP(‘2018-8-31 23:59:59‘) PARTITION p201809 VALUES less than (1538323199), -- 2018-9-30 23:59:59 PARTITION p201810 VALUES less than (1541001599) -- 2018-10-31 23:59:59 );
p201808,p201819,p201810分区的定义顺序依照created_time数值范围从小到大,不能颠倒。insert into article_range values(null,‘MySQL优化‘,‘内容示例‘,1535731180); flush tables; # -- 使操作立即刷新到磁盘文件
1535731180小于1535731199(2018-8-31 23:59:59),因此被存储到p201808分区中,这种算法的存储到哪个分区取决于数据状况。in (值列表))。create table article_list( id int auto_increment, title varchar(64), content text, status TINYINT(1), # -- 文章状态:0-草稿,1-完成但未发布,2-已发布 PRIMARY KEY (id,status) # -- 要求分区依据字段必须是主键的一部分 )charset=utf8 PARTITION BY list(status)( PARTITION writing values in(0,1), # -- 未发布的放在一个分区 PARTITION published values in (2) # -- 已发布的放在一个分区 );
insert into article_list values(null,‘mysql优化‘,‘内容示例‘,0); flush tables;
分区管理语法
range对文章按照月份归档,随着时间的增加,我们需要增加一个月份:alter table article_range add partition( partition p201811 values less than (1543593599) -- select UNIX_TIMESTAMP(‘2018-11-30 23:59:59‘) -- more );
# alter table article_range drop PARTITION p201808
# alter table article_key add partition partitions 4
# alter table article_key coalesce partition 6
key/hash分区的管理不会删除数据,但是每一次调整(新增或销毁分区)都会将所有的数据重写分配到新的分区上。==效率极低==,最好在设计阶段就考虑好分区策略。
分表原因
5.1之后mysql才支持分区操作)id重复的解决方案
memcache、redis的id自增器id一个字段的表,每次自增该字段作为数据记录的id
安装和配置主从复制
Red Hat Enterprise Linux Server release 7.0 (Maipo)(虚拟机)mysql5.7(下载地址)/export/server来存放)# tar xzvf mysql-5.7.23-linux-glibc2.12-x86_64.tar.gz -C /export/server # cd /export/server # mv mysql-5.7.23-linux-glibc2.12-x86_64 mysql
mysql目录的所属组和所属者:# groupadd mysql # useradd -r -g mysql mysql # cd /export/server # chown -R mysql:mysql mysql/ # chmod -R 755 mysql/
mysql数据存放目录(其中/export/data是我创建专门用来为各种服务存放数据的目录)# mkdir /export/data/mysql
mysql服务# cd /export/server/mysql # ./bin/mysqld --basedir=/export/server/mysql --datadir=/export/data/mysql --user=mysql
--pid-file=/export/data/mysql/mysql.pid --initialize
mysql的root账户的初始密码,记下来以备后续登录。如果报错缺少依赖,则使用yum instally依次安装即可my.cnfvim /etc/my.cnf [mysqld] basedir=/export/server/mysql datadir=/export/data/mysql socket=/tmp/mysql.sock user=mysql server-id=10 # 服务id,在集群时必须唯一,建议设置为IP的第四段 port=3306 # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 # Settings user and group are ignored when systemd is used. # If you need to run mysqld under a different user or group, # customize your systemd unit file for mariadb according to the # instructions in http://fedoraproject.org/wiki/Systemd [mysqld_safe] log-error=/export/data/mysql/error.log pid-file=/export/data/mysql/mysql.pid # # include all files from the config directory # !includedir /etc/my.cnf.d
# cp /export/server/mysql/support-files/mysql.server /etc/init.d/mysqld
# service mysqld start
/etc/profile中添加如下内容# mysql env MYSQL_HOME=/export/server/mysql MYSQL_PATH=$MYSQL_HOME/bin PATH=$PATH:$MYSQL_PATH export PATH
# source /etc/profile
root登录mysql -uroot -p # 这里填写之前初始化服务时提供的密码
root账户密码(我为了方便将密码改为root),否则操作数据库会报错set password=password(‘root‘); flush privileges;
use mysql; update user set host=‘%‘ where user=‘root‘; flush privileges;
navicat远程连接虚拟机linux上的mysql了配置主从节点
linux(192.168.10.10)上的mysql为master,宿主机(192.168.10.1)上的mysql为slave配置主从复制。  master的my.cnf如下[mysqld] basedir=/export/server/mysql datadir=/export/data/mysql socket=/tmp/mysql.sock user=mysql server-id=10 port=3306 # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 # Settings user and group are ignored when systemd is used. # If you need to run mysqld under a different user or group, # customize your systemd unit file for mariadb according to the # instructions in http://fedoraproject.org/wiki/Systemd log-bin=mysql-bin # 开启二进制日志 expire-logs-days=7 # 设置日志过期时间,避免占满磁盘 binlog-ignore-db=mysql # 不使用主从复制的数据库 binlog-ignore-db=information_schema binlog-ignore-db=performation_schema binlog-ignore-db=sys binlog-do-db=test #使用主从复制的数据库 [mysqld_safe] log-error=/export/data/mysql/error.log pid-file=/export/data/mysql/mysql.pid # # include all files from the config directory # !includedir /etc/my.cnf.d
master# service mysqld restart
master查看配置是否生效(ON即为开启,默认为OFF):mysql> show variables like ‘log_bin‘; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | log_bin | ON | +---------------+-------+
master的数据库中建立备份账号:backup为用户名,%表示任何远程地址,用户back可以使用密码1234通过任何远程客户端连接master# grant replication slave on *.* to ‘backup‘@‘%‘ identified by ‘1234‘
user表可以看到我们刚创建的用户:mysql> use mysql mysql> select user,authentication_string,host from user; +---------------+-------------------------------------------+-----------+ | user | authentication_string | host | +---------------+-------------------------------------------+-----------+ | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B | % | | mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost | | mysql.sys | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost | | backup | *A4B6157319038724E3560894F7F932C8886EBFCF | % | +---------------+-------------------------------------------+-----------+
test数据库,创建一个article表以备后续测试CREATE TABLE `article` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(64) DEFAULT NULL, `content` text, PRIMARY KEY (`id`) ) CHARSET=utf8;
with read lock表示在此过程中,客户端只能读数据,以便获得一个一致性的快照)[root@zhenganwen ~]# service mysqld restart Shutting down MySQL.... SUCCESS! Starting MySQL. SUCCESS! [root@zhenganwen mysql]# mysql -uroot -proot mysql> flush tables with read lock; Query OK, 0 rows affected (0.00 sec)
master上当前的二进制日志和偏移量(记一下其中的File和Position)mysql> show master status \G *************************** 1. row *************************** File: mysql-bin.000002 Position: 154 Binlog_Do_DB: test Binlog_Ignore_DB: mysql,information_schema,performation_schema,sys Executed_Gtid_Set: 1 row in set (0.00 sec)
File表示实现复制功能的日志,即上图中的Binary log;Position则表示Binary log日志文件的偏移量之后的都会同步到slave中,那么在偏移量之前的则需要我们手动导入。master中导出数据# mysqldump -uroot -proot -hlocalhost test > /export/data/test.sql
test.sql中的内容在slave上执行一遍。配置slave
slave的my.ini文件中的[mysqld]部分# log-bin=mysql # server-id=1 #192.168.10.1
slave,WIN+R->services.msc->MySQL5.7->重新启动slave检查log_bin是否以被开启:# show VARIABLES like ‘log_bin‘;
master的同步复制:stop slave; change master to master_host=‘192.168.10.10‘, # -- master的IP master_user=‘backup‘, # -- 之前在master上创建的用户 master_password=‘1234‘, master_log_file=‘mysql-bin.000002‘, # -- master上 show master status \G 提供的信息 master_log_pos=154;
slave节点并查看状态mysql> start slave; mysql> show slave status \G *************************** 1. row *************************** Slave_IO_State: Waiting for master to send event Master_Host: 192.168.10.10 Master_User: backup Master_Port: 3306 Connect_Retry: 60 Master_Log_File: mysql-bin.000002 Read_Master_Log_Pos: 154 Relay_Log_File: DESKTOP-KUBSPE0-relay-bin.000002 Relay_Log_Pos: 320 Relay_Master_Log_File: mysql-bin.000002 Slave_IO_Running: Yes Slave_SQL_Running: Yes Replicate_Do_DB: Replicate_Ignore_DB: Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: 0 Last_Error: Skip_Counter: 0 Exec_Master_Log_Pos: 154 Relay_Log_Space: 537 Until_Condition: None Until_Log_File: Until_Log_Pos: 0 Master_SSL_Allowed: No Master_SSL_CA_File: Master_SSL_CA_Path: Master_SSL_Cert: Master_SSL_Cipher: Master_SSL_Key: Seconds_Behind_Master: 0 Master_SSL_Verify_Server_Cert: No Last_IO_Errno: 0 Last_IO_Error: Last_SQL_Errno: 0 Last_SQL_Error: Replicate_Ignore_Server_Ids: Master_Server_Id: 10 Master_UUID: f68774b7-0b28-11e9-a925-000c290abe05 Master_Info_File: C:\ProgramData\MySQL\MySQL Server 5.7\Data\master.info SQL_Delay: 0 SQL_Remaining_Delay: NULL Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates Master_Retry_Count: 86400 Master_Bind: Last_IO_Error_Timestamp: Last_SQL_Error_Timestamp: Master_SSL_Crl: Master_SSL_Crlpath: Retrieved_Gtid_Set: Executed_Gtid_Set: Auto_Position: 0 Replicate_Rewrite_DB: Channel_Name: Master_TLS_Version: 1 row in set (0.00 sec)
slave配置成功测试
master的读取锁定# mysql> unlock tables; # Query OK, 0 rows affected (0.00 sec)
master中插入一条数据# mysql> use test # mysql> insert into article (title,content) values (‘mysql master and slave‘,‘record the cluster building succeed!:)‘); # Query OK, 1 row affected (0.00 sec)
slave是否自动同步了数据# mysql> insert into article (title,content) values (‘mysql master and slave‘,‘record the cluster building succeed!:)‘); # Query OK, 1 row affected (0.00 sec)
线上DDL
create table)和维护(alter table)的语言。在线上执行DDL,在低于MySQL5.6版本时会导致全表被独占锁定,此时表处于维护、不可操作状态,这会导致该期间对该表的所有访问无法响应。但是在MySQL5.6之后,支持Online DDL,大大缩短了锁定时间。数据库导入语句
# alter table table-name disable keys
# alter table table-name enable keys
Innodb,那么它==默认会给每条写指令加上事务==(这也会消耗一定的时间),因此建议先手动开启事务,再执行一定量的批量导入,最后手动提交事务。prepare==预编译==一下,这样也能节省很多重复编译的时间。limit offset,rows
offset,比如limit 10000,10相当于对已查询出来的行数弃掉前10000行后再取10行,完全可以加一些条件过滤一下(完成筛选),而不应该使用limit跳过已查询到的数据。这是一个==offset做无用功==的问题。对应实际工程中,要避免出现大页码的情况,尽量引导用户做条件过滤。select * 要少用
select,但这个影响不是很大,因为网络传输多了几十上百字节也没多少延时,并且现在流行的ORM框架都是用的select *,只是我们在设计表的时候注意将大数据量的字段分离,比如商品详情可以单独抽离出一张商品详情表,这样在查看商品简略页面时的加载速度就不会有影响了。order by rand()不要用
select * from student order by rand() limit 5的执行效率就很低,因为它为表中的每条数据都生成随机数并进行排序,而我们只要前5条。单表和多表查询
join、子查询都是涉及到多表的查询。如果你使用explain分析执行计划你会发现多表查询也是一个表一个表的处理,最后合并结果。因此可以说单表查询将计算压力放在了应用程序上,而多表查询将计算压力放在了数据库上。count(*)
MyISAM存储引擎中,会自动记录表的行数,因此使用count(*)能够快速返回。而Innodb内部没有这样一个计数器,需要我们手动统计记录数量,解决思路就是单独使用一张表:| id | table | count | 
|---|---|---|
| 1 | student | 100 | 
limit 1
limit 1,其实ORM框架帮我们做到了这一点(查询单条的操作都会自动加上limit 1)。慢查询日志
开启慢查询日志
slow_query_logshow variables like ‘slov_query_log’查看是否开启,如果状态值为OFF,可以使用set GLOBAL slow_query_log = on来开启,它会在datadir下产生一个xxx-slow.log的文件。设置临界时间
long_query_timeshow VARIABLES like ‘long_query_time‘,单位秒set long_query_time=0.5查看日志
xxx-slow.log中profile信息
profiling开启profile
set profiling=onmysql> show variables like ‘profiling‘; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | profiling | OFF | +---------------+-------+ 1 row in set, 1 warning (0.00 sec) mysql> set profiling=on; Query OK, 0 rows affected, 1 warning (0.00 sec)
查看profile信息
show profilesmysql> show variables like ‘profiling‘; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | profiling | ON | +---------------+-------+ 1 row in set, 1 warning (0.00 sec) mysql> insert into article values (null,‘test profile‘,‘:)‘); Query OK, 1 row affected (0.15 sec) mysql> show profiles; +----------+------------+-------------------------------------------------------+ | Query_ID | Duration | Query | +----------+------------+-------------------------------------------------------+ | 1 | 0.00086150 | show variables like ‘profiling‘ | | 2 | 0.15027550 | insert into article values (null,‘test profile‘,‘:)‘) | +----------+------------+-------------------------------------------------------+
通过Query_ID查看某条SQL所有详细步骤的时间
show profile for query Query_IDshow profiles的结果中,每个SQL有一个Query_ID,可以通过它查看执行该SQL经过了哪些步骤,各消耗了多场时间 典型的服务器配置
max_connections,最大客户端连接数
mysql> show variables like ‘max_connections‘; +-----------------+-------+ | Variable_name | Value | +-----------------+-------+ | max_connections | 151 | +-----------------+-------+
table_open_cache,表文件句柄缓存(表数据是存储在磁盘上的,缓存磁盘文件的句柄方便打开文件读取数据)
mysql> show variables like ‘table_open_cache‘; +------------------+-------+ | Variable_name | Value | +------------------+-------+ | table_open_cache | 2000 | +------------------+-------+
key_buffer_size,索引缓存大小(将从磁盘上读取的索引缓存到内存,可以设置大一些,有利于快速检索)
mysql> show variables like ‘key_buffer_size‘; +-----------------+---------+ | Variable_name | Value | +-----------------+---------+ | key_buffer_size | 8388608 | +-----------------+---------+
innodb_buffer_pool_size,Innodb存储引擎缓存池大小(对于Innodb来说最重要的一个配置,如果所有的表用的都是Innodb,那么甚至建议将该值设置到物理内存的80%,Innodb的很多性能提升如索引都是依靠这个)
mysql> show variables like ‘innodb_buffer_pool_size‘; +-------------------------+---------+ | Variable_name | Value | +-------------------------+---------+ | innodb_buffer_pool_size | 8388608 | +-------------------------+---------+
innodb_file_per_table(innodb中,表数据存放在.ibd文件中,如果将该配置项设置为ON,那么一个表对应一个ibd文件,否则所有innodb共享表空间)
mysqlslap(位于bin目录下)自动生成sql测试
C:\Users\zaw>mysqlslap --auto-generate-sql -uroot -proot mysqlslap: [Warning] Using a password on the command line interface can be insecure. Benchmark Average number of seconds to run all queries: 1.219 seconds Minimum number of seconds to run all queries: 1.219 seconds Maximum number of seconds to run all queries: 1.219 seconds Number of clients running queries: 1 Average number of queries per client: 0
并发测试
C:\Users\zaw>mysqlslap --auto-generate-sql --concurrency=100 -uroot -proot mysqlslap: [Warning] Using a password on the command line interface can be insecure. Benchmark Average number of seconds to run all queries: 3.578 seconds Minimum number of seconds to run all queries: 3.578 seconds Maximum number of seconds to run all queries: 3.578 seconds Number of clients running queries: 100 Average number of queries per client: 0 C:\Users\zaw>mysqlslap --auto-generate-sql --concurrency=150 -uroot -proot mysqlslap: [Warning] Using a password on the command line interface can be insecure. Benchmark Average number of seconds to run all queries: 5.718 seconds Minimum number of seconds to run all queries: 5.718 seconds Maximum number of seconds to run all queries: 5.718 seconds Number of clients running queries: 150 Average number of queries per client: 0
多轮测试
C:\Users\zaw>mysqlslap --auto-generate-sql --concurrency=150 --iterations=10 -uroot -proot mysqlslap: [Warning] Using a password on the command line interface can be insecure. Benchmark Average number of seconds to run all queries: 5.398 seconds Minimum number of seconds to run all queries: 4.313 seconds Maximum number of seconds to run all queries: 6.265 seconds Number of clients running queries: 150 Average number of queries per client: 0
存储引擎测试
C:\Users\zaw>mysqlslap --auto-generate-sql --concurrency=150 --iterations=3 --engine=innodb -uroot -proot mysqlslap: [Warning] Using a password on the command line interface can be insecure. Benchmark Running for engine innodb Average number of seconds to run all queries: 5.911 seconds Minimum number of seconds to run all queries: 5.485 seconds Maximum number of seconds to run all queries: 6.703 seconds Number of clients running queries: 150 Average number of queries per client: 0
C:\Users\zaw>mysqlslap --auto-generate-sql --concurrency=150 --iterations=3 --engine=myisam -uroot -proot mysqlslap: [Warning] Using a password on the command line interface can be insecure. Benchmark Running for engine myisam Average number of seconds to run all queries: 53.104 seconds Minimum number of seconds to run all queries: 46.843 seconds Maximum number of seconds to run all queries: 60.781 seconds Number of clients running queries: 150 Average number of queries per client: 0
slave不能写只能读(如果对slave执行写操作,那么show slave status将会呈现Slave_SQL_Running=NO,此时你需要按照前面提到的手动同步一下slave)。DataBase一样,我们可以抽取出ReadDataBase,WriteDataBase implements DataBase,但是这种方式无法利用优秀的线程池技术如DruidDataSource帮我们管理连接,也无法利用Spring AOP让连接对DAO层透明。方案二、使用Spring AOP
Spring AOP解决数据源切换的问题,那么就可以和Mybatis、Druid整合到一起了。Spring1和Mybatis时,我们只需写DAO接口和对应的SQL语句,那么DAO实例是由谁创建的呢?实际上就是Spring帮我们创建的,它通过我们注入的数据源,帮我们完成从中获取数据库连接、使用连接执行 SQL 语句的过程以及最后归还连接给数据源的过程。addXXX/createXXX、删deleteXX/removeXXX、改updateXXXX、查selectXX/findXXX/getXX/queryXXX)动态地选择数据源(读数据源对应连接master而写数据源对应连接slave),那么就可以做到读写分离了。项目结构
mybatis和druid,实现数据源动态切换主要依赖spring-aop和spring-aspects 
<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.0.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.0.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.0.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.6</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.22</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.0.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>
数据类
package top.zhenganwen.mysqloptimize.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Article { private int id; private String title; private String content; }
spring配置文件
RoutingDataSourceImpl是实现动态切换功能的核心类,稍后介绍。 
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="db.properties"></context:property-placeholder> <context:component-scan base-package="top.zhenganwen.mysqloptimize"/> <bean id="slaveDataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${db.driverClass}"/> <property name="url" value="${master.db.url}"></property> <property name="username" value="${master.db.username}"></property> <property name="password" value="${master.db.password}"></property> </bean> <bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${db.driverClass}"/> <property name="url" value="${slave.db.url}"></property> <property name="username" value="${slave.db.username}"></property> <property name="password" value="${slave.db.password}"></property> </bean> <bean id="dataSourceRouting" class="top.zhenganwen.mysqloptimize.dataSource.RoutingDataSourceImpl"> <property name="defaultTargetDataSource" ref="masterDataSource"></property> <property name="targetDataSources"> <map key-type="java.lang.String" value-type="javax.sql.DataSource"> <entry key="read" value-ref="slaveDataSource"/> <entry key="write" value-ref="masterDataSource"/> </map> </property> <property name="methodType"> <map key-type="java.lang.String" value-type="java.lang.String"> <entry key="read" value="query,find,select,get,load,"></entry> <entry key="write" value="update,add,create,delete,remove,modify"/> </map> </property> </bean> <!-- Mybatis文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="dataSource" ref="dataSourceRouting" /> <property name="mapperLocations" value="mapper/*.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="top.zhenganwen.mysqloptimize.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> </beans>
dp.properties 
master.db.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC master.db.username=root master.db.password=root slave.db.url=jdbc:mysql://192.168.10.10:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC slave.db.username=root slave.db.password=root db.driverClass=com.mysql.jdbc.Driver
mybatis-config.xml 
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAlias type="top.zhenganwen.mysqloptimize.entity.Article" alias="Article"/> </typeAliases> </configuration>
mapper接口和配置文件
ArticleMapper.java 
package top.zhenganwen.mysqloptimize.mapper; import org.springframework.stereotype.Repository; import top.zhenganwen.mysqloptimize.entity.Article; import java.util.List; @Repository public interface ArticleMapper { List<Article> findAll(); void add(Article article); void delete(int id); }
ArticleMapper.xml 
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="top.zhenganwen.mysqloptimize.mapper.ArticleMapper"> <select id="findAll" resultType="Article"> select * from article </select> <insert id="add" parameterType="Article"> insert into article (title,content) values (#{title},#{content}) </insert> <delete id="delete" parameterType="int"> delete from article where id=#{id} </delete> </mapper>
核心类
RoutingDataSourceImpl
 
package top.zhenganwen.mysqloptimize.dataSource; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import java.util.*; /** * RoutingDataSourceImpl class * 数据源路由 * * @author zhenganwen, blog:zhenganwen.top * @date 2018/12/29 */ public class RoutingDataSourceImpl extends AbstractRoutingDataSource { /** * key为read或write * value为DAO方法的前缀 * 什么前缀开头的方法使用读数据员,什么开头的方法使用写数据源 */ public static final Map<String, List<String>> METHOD_TYPE_MAP = new HashMap<String, List<String>>(); /** * 由我们指定数据源的id,由Spring切换数据源 * * @return */ @Override protected Object determineCurrentLookupKey() { System.out.println("数据源为:"+DataSourceHandler.getDataSource()); return DataSourceHandler.getDataSource(); } public void setMethodType(Map<String, String> map) { for (String type : map.keySet()) { String methodPrefixList = map.get(type); if (methodPrefixList != null) { METHOD_TYPE_MAP.put(type, Arrays.asList(methodPrefixList.split(","))); } } } }
Spring动态代理DAO接口时直接使用该数据源,现在我们有了读、写两个数据源,我们需要加入一些自己的逻辑来告诉调用哪个接口使用哪个数据源(读数据的接口使用slave,写数据的接口使用master。这个告诉Spring该使用哪个数据源的类就是AbstractRoutingDataSource,必须重写的方法determineCurrentLookupKey返回数据源的标识,结合spring配置文件(下段代码的5,6两行) 
<bean id="dataSourceRouting" class="top.zhenganwen.mysqloptimize.dataSource.RoutingDataSourceImpl"> <property name="defaultTargetDataSource" ref="masterDataSource"></property> <property name="targetDataSources"> <map key-type="java.lang.String" value-type="javax.sql.DataSource"> <entry key="read" value-ref="slaveDataSource"/> <entry key="write" value-ref="masterDataSource"/> </map> </property> <property name="methodType"> <map key-type="java.lang.String" value-type="java.lang.String"> <entry key="read" value="query,find,select,get,load,"></entry> <entry key="write" value="update,add,create,delete,remove,modify"/> </map> </property> </bean>
determineCurrentLookupKey返回read那么使用slaveDataSource,如果返回write就使用masterDataSource。DataSourceHandler
 
package top.zhenganwen.mysqloptimize.dataSource; /** * DataSourceHandler class * <p> * 将数据源与线程绑定,需要时根据线程获取 * * @author zhenganwen, blog:zhenganwen.top * @date 2018/12/29 */ public class DataSourceHandler { /** * 绑定的是read或write,表示使用读或写数据源 */ private static final ThreadLocal<String> holder = new ThreadLocal<String>(); public static void setDataSource(String dataSource) { System.out.println(Thread.currentThread().getName()+"设置了数据源类型"); holder.set(dataSource); } public static String getDataSource() { System.out.println(Thread.currentThread().getName()+"获取了数据源类型"); return holder.get(); } }
DataSourceAspect
 
package top.zhenganwen.mysqloptimize.dataSource; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.stereotype.Component; import java.util.List; import java.util.Set; import static top.zhenganwen.mysqloptimize.dataSource.RoutingDataSourceImpl.METHOD_TYPE_MAP; /** * DataSourceAspect class * * 配置切面,根据方法前缀设置读、写数据源 * 项目启动时会加载该bean,并按照配置的切面(哪些切入点、如何增强)确定动态代理逻辑 * @author zhenganwen,blog:zhenganwen.top * @date 2018/12/29 */ @Component //声明这是一个切面,这样Spring才会做相应的配置,否则只会当做简单的bean注入 @Aspect @EnableAspectJAutoProxy public class DataSourceAspect { /** * 配置切入点:DAO包下的所有类的所有方法 */ @Pointcut("execution(* top.zhenganwen.mysqloptimize.mapper.*.*(..))") public void aspect() { } /** * 配置前置增强,对象是aspect()方法上配置的切入点 */ @Before("aspect()") public void before(JoinPoint point) { String className = point.getTarget().getClass().getName(); String invokedMethod = point.getSignature().getName(); System.out.println("对 "+className+"$"+invokedMethod+" 做了前置增强,确定了要使用的数据源类型"); Set<String> dataSourceType = METHOD_TYPE_MAP.keySet(); for (String type : dataSourceType) { List<String> prefixList = METHOD_TYPE_MAP.get(type); for (String prefix : prefixList) { if (invokedMethod.startsWith(prefix)) { DataSourceHandler.setDataSource(type); System.out.println("数据源为:"+type); return; } } } } }
slave中读的呢?可以将写后复制到slave中的数据更改,再读该数据就知道是从slave中读了。==注意==,一但对slave做了写操作就要重新手动将slave与master同步一下,否则主从复制就会失效。  
package top.zhenganwen.mysqloptimize.dataSource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import top.zhenganwen.mysqloptimize.entity.Article; import top.zhenganwen.mysqloptimize.mapper.ArticleMapper; (SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring-mybatis.xml") public class RoutingDataSourceTest { ArticleMapper articleMapper; public void testRead() { System.out.println(articleMapper.findAll()); } public void testAdd() { Article article = new Article(0, "我是新插入的文章", "测试是否能够写到master并且复制到slave中"); articleMapper.add(article); } public void testDelete() { articleMapper.delete(2); } }
负载均衡算法
高可用

原文:https://www.cnblogs.com/yangmaosen/p/12507960.html