为何要优化java
如何优化node
原则:尽可能使用整型表示字符串mysql
# INET_ATON(str),address to number # INET_NTOA(number),number to address
enum
原则:定长和非定长数据类型的选择linux
# decimal不会损失精度,存储空间会随数据的增大而增大。double占用固定空间,较大数的存储会损失精度。非定长的还有varchar、text
金额redis
# 对数据的精度要求较高,小数的运算和存储存在精度问题(不能将全部小数转换成二进制)
# 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 ‘’
原则:字段注释要完整,见名知意spring
原则:单表字段不宜过多sql
原则:能够预留字段数据库
# 在使用以上原则以前首先要知足业务需求
# 外键foreign key只能实现一对一或一对多的映射
item
)和商品的详细信息(item_intro
),一般使用相同的主键或者增长一个外键字段(item_id
)
# 数据表的设计规范,一套愈来愈严格的规范体系(若是须要知足N范式,首先要知足N-1范式)。N
java
的文章)第二范式:消除对主键的部分依赖vim
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 、MYI 3个文件 |
否,由于关联的还有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.cnf
vim /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_log
show variables like ‘slov_query_log’
查看是否开启,若是状态值为OFF
,可使用set GLOBAL slow_query_log = on
来开启,它会在datadir
下产生一个xxx-slow.log
的文件。设置临界时间
long_query_time
show VARIABLES like 'long_query_time'
,单位秒set long_query_time=0.5
查看日志
xxx-slow.log
中profile信息
profiling
开启profile
set profiling=on
mysql> 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 profiles
mysql> 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_ID
show 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
层透明。方案2、使用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); } }
负载均衡算法
高可用