概述
java
字段類型的選擇,設計規範,範式,常見設計案例node
INET_ATON(str),address to numbermysql
INET_NTOA(number),number to addresslinux
可是由於維護成本較高所以不常使用,使用關聯表的方式來替代enumredis
decimal不會損失精度,存儲空間會隨數據的增大而增大。double佔用固定空間,較大數的存儲會損失精度。非定長的還有varchar、text算法
對數據的精度要求較高,小數的運算和存儲存在精度問題(不能將全部小數轉換成二進制)spring
price decimal(8,2)有2位小數的定點數,定點數支持很大的數(甚至是超過int,bigint存儲範圍的數)sql
元->分數據庫
定長char,非定長varchar、text(上限65535,其中varchar還會消耗1-3字節記錄長度,而text使用額外空間記錄長度)vim
非null字段的處理要比null字段的處理高效些!且不須要判斷是否爲null。
null在MySQL中,很差處理,存儲須要額外空間,運算也須要特殊的運算符。如select null = null和select null <> null(<>爲不等號)有着一樣的結果,只能經過is null和is not null來判斷字段是否爲null。
如何存儲?MySQL中每條記錄都須要額外的存儲空間,表示每一個字段是否爲null。所以一般使用特殊的數據進行佔位,好比int not null default 0、string not null default ‘’
二三十個就極限了
關聯表的設計在使用以上原則以前首先要知足業務需求
外鍵foreign key只能實現一對一或一對多的映射
使用外鍵
單獨新建一張表將多對多拆分紅兩個一對多
如商品的基本信息(item)和商品的詳細信息(item_intro),一般使用相同的主鍵或者增長一個外鍵字段(item_id)
範式 Normal Format數據表的設計規範,一套愈來愈嚴格的規範體系(若是須要知足N範式,首先要知足N-1範式)。N
字段原子性,字段不可再分割。
關係型數據庫,默認知足第一範式
注意比較容易出錯的一點,在一對多的設計中使用逗號分隔多個外鍵,這種方法雖然存儲方便,但不利於維護和索引(好比查找帶標籤java的文章)
即在表中加上一個與業務邏輯無關的字段做爲主鍵
主鍵:能夠惟一標識記錄的字段或者字段集合。
course_name | course_class | weekday(周幾) | course_teacher |
---|---|---|---|
MySQL | 教育大樓1525 | 週一 | 張三 |
Java | 教育大樓1521 | 週三 | 李四 |
MySQL | 教育大樓1521 | 週五 | 張三 |
依賴:A字段能夠肯定B字段,則B字段依賴A字段。好比知道了下一節課是數學課,就能肯定任課老師是誰。因而周幾和下一節課和就能構成複合主鍵,可以肯定去哪一個教室上課,任課老師是誰等。但咱們經常增長一個id做爲主鍵,而消除對主鍵的部分依賴。
對主鍵的部分依賴:某個字段依賴複合主鍵中的一部分。
解決方案:新增一個獨立字段做爲主鍵。
傳遞依賴:B字段依賴於A,C字段又依賴於B。好比上例中,任課老師是誰取決因而什麼課,是什麼課又取決於主鍵id。所以須要將此表拆分爲兩張表日程表和課程表(獨立數據獨立建表):
id | weekday | course_class | course_id |
---|---|---|---|
1001 | 週一 | 教育大樓1521 | 3546 |
course_id | course_name | course_teacher |
---|---|---|
3546 | Java | 張三 |
這樣就減小了數據的冗餘(即便週一至週日天天都有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
行級鎖(row-level lock):鎖定的是一行或幾行記錄。共享鎖:select * from
若是沒有特別的需求,使用默認的Innodb便可。
MyISAM:以讀寫插入爲主的應用程序,好比博客系統、新聞門戶網站。
Innodb:更新(刪除)操做頻率也高,或者要保證數據的完整性;併發量高,支持事務和外鍵保證數據完整性。好比OA自動化辦公系統。
索引關鍵字與數據的映射關係稱爲索引(==包含關鍵字和對應的記錄在磁盤中的地址==)。關鍵字是從數據當中提取的用於標識、檢索數據的特定內容。
圖書館爲每本書都加了索引號(類別-樓層-書架)、字典爲詞語解釋按字母順序編寫目錄等都用到了索引。
普通索引(key),惟一索引(unique key),主鍵索引(primary key),全文索引(fulltext key)
三種索引的索引方式是同樣的,只不過對索引的關鍵字有不一樣的限制:
show create table 表名:
desc 表名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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:
1
2
3
4
5
6
7
8
9
10
|
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 索引名
1
2
3
|
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(由於主鍵只有一個)。這裏值得注意的是,若是主鍵自增加,那麼不能直接執行此操做(自增加依賴於主鍵索引):
須要取消自增加再行刪除:
1
2
3
4
|
alter table user_index
-- 從新定義字段
MODIFY id int,
drop PRIMARY KEY
|
但一般不會刪除主鍵,由於設計主鍵必定與業務邏輯無關。
1
2
3
4
5
6
7
8
9
10
11
|
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語句執行前的執行計劃:
由上圖可看出此SQL語句是按照主鍵索引來檢索的。
執行計劃是:當執行SQL語句時,首先會分析、優化,造成執行計劃,在按照執行計劃執行。
上圖中,根據id查詢記錄,由於id字段僅創建了主鍵索引,所以此SQL執行可選的索引只有主鍵索引,若是有多個,最終會選一個較優的做爲檢索的依據。
1
2
3
4
|
-- 增長一個沒有創建索引的字段
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或索引覆蓋),索引也不必定被使用
好比下面兩條SQL語句在語義上相同,可是第一條會使用主鍵索引而第二條不會。
1
2
|
select * from user where id = 20-1;
select * from user where id+1 = 20;
|
好比搜索標題包含mysql的文章:
1
|
select * from article where title like '%mysql%';
|
這種SQL的執行計劃用不了索引(like語句匹配表達式以通配符開頭),所以只能作全表掃描,效率極低,在實際工程中幾乎不被採用。而通常會使用第三方提供的支持中文的全文索引來作。
可是 關鍵字查詢 熱搜提醒功能仍是能夠作的,好比鍵入mysql以後提醒mysql 教程、mysql 下載、mysql 安裝步驟等。用到的語句是:
1
|
select * from article where title like 'mysql%';
|
這種like是能夠利用索引的(固然前提是title字段創建過索引)。
創建複合索引:
1
|
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 = ?的記錄,二者取交集。
一但有一邊無索引可用就會致使整個SQL語句的全表掃描
如性別、支付狀態等狀態值字段每每只有極少的幾種取值可能,這種字段即便創建索引,也每每利用不上。這是由於,一個狀態值可能匹配大量的記錄,這種狀況MySQL會認爲利用索引比全表掃描的效率低,從而棄用索引。索引是隨機訪問磁盤,而全表掃描是順序訪問磁盤,這就比如有一棟20層樓的寫字樓,樓底下的索引牌上寫着某個公司對應不相鄰的幾層樓,你去公司找人,與其按照索引牌的提示去其中一層樓沒找到再下來看索引牌再上樓,不如從1樓挨個往上找到頂樓。
語法:index(field(10)),使用字段值的前10個字符創建索引,默認是使用字段的所有內容創建索引。
前提:前綴的標識度高。好比密碼就適合創建前綴索引,由於密碼幾乎各不相同。
==實操的難度==:在於前綴截取的長度。
咱們能夠利用select count(*)/count(distinct left(password,prefixLen));,經過從調整prefixLen的值(從1自增)查看不一樣前綴長度的一個平均匹配度,接近1時就能夠了(表示一個密碼的前prefixLen個字符幾乎能肯定惟一一條記錄)
btree(多路平衡查找樹)是一種普遍應用於==磁盤上實現索引功能==的一種數據結構,也是大多數數據庫索引表的實現。
以add index(first_name,last_name)爲例:
BTree的一個node能夠存儲多個關鍵字,node的大小取決於計算機的文件系統,所以咱們能夠經過減少索引字段的長度使結點存儲更多的關鍵字。若是node中的關鍵字已滿,那麼能夠經過每一個關鍵字之間的子節點指針來拓展索引表,可是不能破壞結構的有序性,好比按照first_name第一有序、last_name第二有序的規則,新添加的韓香就能夠插到韓康以後。白起 < 韓飛 < 韓康 < 李世民 < 趙奢 < 李尋歡 < 王語嫣 < 楊不悔。這與二叉搜索樹的思想是同樣的,只不過二叉搜索樹的查找效率是log(2,N)(以2爲底N的對數),而BTree的查找效率是log(x,N)(其中x爲node的關鍵字數量,能夠達到1000以上)。
從log(1000+,N)能夠看出,少許的磁盤讀取便可作到大量數據的遍歷,這也是btree的設計目的。
聚簇結構(也是在BTree上升級改造的)中,關鍵字和記錄是存放在一塊兒的。
在MySQL中,僅僅只有Innodb的==主鍵索引爲聚簇結構==,其它的索引包括Innodb的非主鍵索引都是典型的BTree結構。
在索引被載入內存時,使用哈希結構來存儲。
查詢緩存緩存select語句的查詢結果
windows上是my.ini,linux上是my.cnf
在[mysqld]段中配置query_***_type:
更改配置後須要重啓以使配置生效,重啓後可經過show variables like ‘query_***_type’;來查看:
1
2
|
show variables like 'query_***_type';
query_***_type DEMAND
|
經過配置項query_***_size來設置:
1
2
3
4
5
6
|
show variables like 'query_***_size';
query_***_size 0
set global query_***_size=64*1024*1024;
show variables like 'query_***_size';
query_***_size 67108864
|
select sql_*** * from user;
reset query ***;
當數據表改動時,基於該數據表的任何緩存都會被刪除。(表層面的管理,不是記錄層面的管理,所以失效率較高)
通常狀況下咱們建立的表對應一組存儲文件,使用MyISAM存儲引擎時是一個.MYI和.MYD文件,使用Innodb存儲引擎時是一個.ibd和.frm(表結構)文件。
當數據量較大時(通常千萬條記錄級別以上),MySQL的性能就會開始降低,這時咱們就須要將數據分散到多組存儲文件,==保證其單個文件的執行效率==。
最多見的分區方案是按id分區,以下將id的哈希值對10取模將數據均勻分散到10個.ibd存儲文件中:
1
2
3
4
5
|
create table article(
id int auto_increment PRIMARY KEY,
title varchar(64),
content text
)PARTITION by HASH(id) PARTITIONS 10
|
查看data目錄:
==服務端的表分區對於客戶端是透明的==,客戶端仍是照常插入數據,但服務端會按照分區算法分散存儲數據。
==分區依據的字段必須是主鍵的一部分==,分區是爲了快速定位數據,所以該字段的搜索頻次較高應做爲強檢索字段,不然依照該字段分區毫無心義
相同的輸入獲得相同的輸出。輸出的結果跟輸入是否具備規律無關。==僅適用於整型字段==
和hash(field)的性質同樣,只不過key是==處理字符串==的,比hash()多了一步從字符串中計算出一個整型在作取模操做。
1
2
3
4
5
6
|
create table article_key(
id int auto_increment,
title varchar(64),
content text,
PRIMARY KEY (id,title) -- 要求分區依據字段必須是主鍵的一部分
)PARTITION by KEY(title) PARTITIONS 10
|
是一種==條件分區==算法,按照數據大小範圍分區(將數據使用某種條件,分散到不一樣的分區中)。
以下,按文章的發佈時間將數據按照2018年8月、9月、10月分區存放:
1
2
3
4
5
6
7
8
9
10
11
12
|
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
);
|
注意:條件運算符只能使用==less than==,這覺得着較小的範圍要放在前面,好比上述p201808,p201819,p201810分區的定義順序依照created_time數值範圍從小到大,不能顛倒。
1
2
|
insert into article_range values(null,'MySQL優化','內容示例',1535731180);
flush tables; -- 使操做當即刷新到磁盤文件
|
因爲插入的文章的發佈時間1535731180小於1535731199(2018-8-31 23:59:59),所以被存儲到p201808分區中,這種算法的存儲到哪一個分區取決於數據情況。
也是一種條件分區,按照列表值分區(in (值列表))。
1
2
3
4
5
6
7
8
9
10
11
|
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) -- 已發佈的放在一個分區
);
|
1
2
|
insert into article_list values(null,'mysql優化','內容示例',0);
flush tables;
|
前文中咱們嘗試使用range對文章按照月份歸檔,隨着時間的增長,咱們須要增長一個月份:
1
2
3
4
|
alter table article_range add partition(
partition p201811 values less than (1543593599) -- select UNIX_TIMESTAMP('2018-11-30 23:59:59')
-- more
);
|
1
|
alter table article_range drop PARTITION p201808
|
注意:==刪除分區後,分區中原有的數據也會隨之刪除!==
1
|
alter table article_key add partition partitions 4
|
1
|
alter table article_key coalesce partition 6
|
key/hash分區的管理不會刪除數據,可是每一次調整(新增或銷燬分區)都會將全部的數據重寫分配到新的分區上。==效率極低==,最好在設計階段就考慮好分區策略。
當數據表中的數據量很大時,分區帶來的效率提高才會顯現出來。
只有檢索字段爲分區字段時,分區帶來的效率提高才會比較明顯。所以,==分區字段的選擇很重要==,而且==業務邏輯要儘量地根據分區字段作相應調整==(儘可能使用分區字段做爲查詢條件)。
水平分割和垂直分割水平分割:經過創建結構相同的幾張表分別存儲數據
垂直分割:將常常一塊兒使用的字段放在一個單獨的表中,分割後的表記錄之間是一一對應關係。
橫向擴展:從根本上(單機的硬件處理能力有限)提高數據庫性能 。由此而生的相關技術:==讀寫分離、負載均衡==
解壓到對外提供的服務的目錄(我本身專門建立了一個/export/server來存放)
1
2
3
|
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目錄的所屬組和所屬者:
1
2
3
4
5
|
groupadd mysql
useradd -r -g mysql mysql
cd /export/server
chown -R mysql:mysql mysql/
chmod -R 755 mysql/
|
建立mysql數據存放目錄(其中/export/data是我建立專門用來爲各類服務存放數據的目錄)
1
|
mkdir /export/data/mysql
|
初始化mysql服務
1
2
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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
|
將服務添加到開機自動啓動
1
|
cp /export/server/mysql/support-files/mysql.server /etc/init.d/mysqld
|
啓動服務
1
|
service mysqld start
|
配置環境變量,在/etc/profile中添加以下內容
1
2
3
4
5
|
# mysql env
MYSQL_HOME=/export/server/mysql
MYSQL_PATH=$MYSQL_HOME/bin
PATH=$PATH:$MYSQL_PATH
export PATH
|
使配置便可生效
1
|
source /etc/profile
|
使用root登陸
1
2
|
mysql -uroot -p
# 這裏填寫以前初始化服務時提供的密碼
|
登陸上去以後,更改root帳戶密碼(我爲了方便將密碼改成root),不然操做數據庫會報錯
1
2
|
set password=password('root');
flush privileges;
|
設置服務可被全部遠程客戶端訪問
1
2
3
|
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以下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
[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
1
|
service mysqld restart
|
登陸master查看配置是否生效(ON即爲開啓,默認爲OFF):
1
2
3
4
5
6
|
mysql> show variables like 'log_bin';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_bin | ON |
+---------------+-------+
|
在master的數據庫中創建備份帳號:backup爲用戶名,%表示任何遠程地址,用戶back可使用密碼1234經過任何遠程客戶端鏈接master
1
|
grant replication slave on *.* to 'backup'@'%' identified by '1234'
|
查看user表能夠看到咱們剛建立的用戶:
1
2
3
4
5
6
7
8
9
10
|
mysql> use mysql
mysql> select user,authentication_string,host from user;
+---------------+-------------------------------------------+-----------+
| user | authentication_string | host |
+---------------+-------------------------------------------+-----------+
| root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B | % |
| mysql.session | *TH***NOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| mysql.sys | *TH***NOTAVALIDPASSWORDTHATCANBEUSEDHERE | localhost |
| backup | *A4B6157319038724E3560894F7F932C8886EBFCF | % |
+---------------+-------------------------------------------+-----------+
|
新建test數據庫,建立一個article表以備後續測試
1
2
3
4
5
6
|
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表示在此過程當中,客戶端只能讀數據,以便得到一個一致性的快照)
1
2
3
4
5
6
|
[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)
1
2
3
4
5
6
7
8
|
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中,那麼在偏移量以前的則須要咱們手動導入。
主服務器上面的任何修改都會保存在二進制日誌Binary log裏面,從服務器上面啓動一個I/O thread(實際上就是一個主服務器的客戶端進程),鏈接到主服務器上面請求讀取二進制日誌,而後把讀取到的二進制日誌寫到本地的一個Realy log裏面。從服務器上面開啓一個SQL thread定時檢查Realy log,若是發現有更改當即把更改的內容在本機上面執行一遍。
若是一主多從的話,這時主庫既要負責寫又要負責爲幾個從庫提供二進制日誌。此時能夠稍作調整,將二進制日誌只給某一從,這一從再開啓二進制日誌並將本身的二進制日誌再發給其它從。或者是乾脆這個從不記錄只負責將二進制日誌轉發給其它從,這樣架構起來性能可能要好得多,並且數據之間的延時應該也稍微要好一些
手動導入,從master中導出數據
1
|
mysqldump -uroot -proot -hlocalhost test > /export/data/test.sql
|
將test.sql中的內容在slave上執行一遍。
修改slave的my.ini文件中的[mysqld]部分
1
2
|
log-bin=mysql
server-id=1 #192.168.10.1
|
保存修改後重啓slave,WIN+R->services.msc->MySQL5.7->從新啓動
登陸slave檢查log_bin是否以被開啓:
1
|
show VARIABLES like 'log_bin';
|
配置與master的同步複製:
1
2
3
4
5
6
7
|
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節點並查看狀態
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
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)
|
注意查看第四、1四、15三行,若與我一致,表示slave配置成功
關閉master的讀取鎖定
1
2
|
mysql> unlock tables;
Query OK, 0 rows affected (0.00 sec)
|
向master中插入一條數據
1
2
3
|
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是否自動同步了數據
1
2
|
mysql> insert into article (title,content) values ('mysql master and slave','record the cluster building succeed!:)');
Query OK, 1 row affected (0.00 sec)
|
至此,主從複製的配置成功!:)
使用mysqlreplicate命令快速搭建 Mysql 主從複製
讀寫分離是依賴於主從複製,而主從複製又是爲讀寫分離服務的。由於主從複製要求slave不能寫只能讀(若是對slave執行寫操做,那麼show slave status將會呈現Slave_SQL_Running=NO,此時你須要按照前面提到的手動同步一下slave)。
就像咱們在學JDBC時定義的DataBase同樣,咱們能夠抽取出ReadDataBase,WriteDataBase implements DataBase,可是這種方式沒法利用優秀的線程池技術如DruidDataSource幫咱們管理鏈接,也沒法利用Spring AOP讓鏈接對DAO層透明。
若是可以使用Spring AOP解決數據源切換的問題,那麼就能夠和Mybatis、Druid整合到一塊兒了。
咱們在整合Spring1和Mybatis時,咱們只需寫DAO接口和對應的SQL語句,那麼DAO實例是由誰建立的呢?實際上就是Spring幫咱們建立的,它經過咱們注入的數據源,幫咱們完成從中獲取數據庫鏈接、使用鏈接執行SQL語句的過程以及最後歸還鏈接給數據源的過程。
若是咱們能在調用DAO接口時根據接口方法命名規範(增addXXX/createXXX、刪deleteXX/removeXXX、改updateXXXX、查selectXX/findXXX/getXX/queryXXX)動態地選擇數據源(讀數據源對應鏈接master而寫數據源對應鏈接slave),那麼就能夠作到讀寫分離了。
其中,爲了方便訪問數據庫引入了mybatis和druid,實現數據源動態切換主要依賴spring-aop和spring-aspects
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
1.3.2
3.4.6
5.0.8.RELEASE
5.0.8.RELEASE
5.0.8.RELEASE
1.1.6
6.0.2
5.0.8.RELEASE
5.0.8.RELEASE
1.16.22
5.0.8.RELEASE
4.12
|
1
2
3
4
5
6
7
8
9
10
11
12
|
package top.zhenganwen.mysqloptimize.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; <a href="/profile/1954537" data-card-uid="1954537" class="" target="_blank" style="color: #25bb9b" data-card-index="3">@Data @AllArgsConstructor
@NoArgsConstructor
public class Article {
private int id;
private String title;
private String content;
}
|
其中RoutingDataSourceImpl是實現動態切換功能的核心類,稍後介紹。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
<?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: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 name="username" value="${master.db.username}">
<property name="password" value="${master.db.password}">
<bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${db.driverClass}"/>
<property name="url" value="${slave.db.url}">
<property name="username" value="${slave.db.username}">
<property name="password" value="${slave.db.password}">
<bean id="dataSourceRouting" class="top.zhenganwen.mysqloptimize.dataSource.RoutingDataSourceImpl">
<property name="defaultTargetDataSource" ref="masterDataSource">
<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"/>
<property name="methodType">
<map key-type="java.lang.String" value-type="java.lang.String">
<entry key="read" value="query,find,select,get,load,">
<entry key="write" value="update,add,create,delete,remove,modify"/>
<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 class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="top.zhenganwen.mysqloptimize.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
|
dp.properties
1
2
3
4
5
6
7
8
9
|
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
1
2
3
4
5
6
7
8
9
|
<?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">
<typeAlias type="top.zhenganwen.mysqloptimize.entity.Article" alias="Article"/>
|
ArticleMapper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package top.zhenganwen.mysqloptimize.mapper;
import org.springframework.stereotype.Repository;
import top.zhenganwen.mysqloptimize.entity.Article;
import java.util.List;
@Repository
public interface ArticleMapper {
ListfindAll();
void add(Article article);
void delete(int id);
}
|
ArticleMapper.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?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
<insert id="add" parameterType="Article">
insert into article (title,content) values (#{title},#{content})
<delete id="delete" parameterType="int">
delete from article where id=#{id}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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, Listnew HashMap<String, List
/**
* 由咱們指定數據源的id,由Spring切換數據源
*
* @return */ <a href="/profile/992988" data-card-uid="992988" class="" target="_blank" style="color: #25bb9b" data-card-index="5">@Override protected Object determineCurrentLookupKey() {
System.out.println("數據源爲:"+DataSourceHandler.getDataSource());
return DataSourceHandler.getDataSource();
}
public void setMethodType(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兩行)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<bean id="dataSourceRouting" class="top.zhenganwen.mysqloptimize.dataSource.RoutingDataSourceImpl">
<property name="defaultTargetDataSource" ref="masterDataSource">
<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"/>
<property name="methodType">
<map key-type="java.lang.String" value-type="java.lang.String">
<entry key="read" value="query,find,select,get,load,">
<entry key="write" value="update,add,create,delete,remove,modify"/>
|
若是determineCurrentLookupKey返回read那麼使用slaveDataSource,若是返回write就使用masterDataSource。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package top.zhenganwen.mysqloptimize.dataSource;
/**
* DataSourceHandler class
*
* 將數據源與線程綁定,須要時根據線程獲取
*
* @author zhenganwen, blog:zhenganwen.top
* @date 2018/12/29
*/
public class DataSourceHandler {
/**
* 綁定的是read或write,表示使用讀或寫數據源
*/
private static final ThreadLocalnew ThreadLocal
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();
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
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
*/ <a href="/profile/664319079" data-card-uid="664319079" class="" target="_blank" style="color: #25bb9b" data-card-index="6">@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
for (String type : dataSourceType) {
List
for (String prefix : prefixList) {
if (invokedMethod.startsWith(prefix)) {
DataSourceHandler.setDataSource(type);
System.out.println("數據源爲:"+type);
return;
}
}
}
}
}
|
如何測試讀是從slave中讀的呢?能夠將寫後複製到slave中的數據更改,再讀該數據就知道是從slave中讀了。==注意==,一但對slave作了寫操做就要從新手動將slave與master同步一下,不然主從複製就會失效。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
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.SpringJUnit4Cla***unner;
import top.zhenganwen.mysqloptimize.entity.Article;
import top.zhenganwen.mysqloptimize.mapper.ArticleMapper;
@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration(locations = "classpath:spring-mybatis.xml")
public class RoutingDataSourceTest {
@Autowired
ArticleMapper articleMapper;
@Test
public void testRead() {
System.out.println(articleMapper.findAll());
}
@Test
public void testAdd() {
Article article = new Article(0, "我是新插入的文章", "測試是否可以寫到master而且複製到slave中");
articleMapper.add(article);
}
@Test
public void testDelete() {
articleMapper.delete(2);
}
}
|
在服務器架構時,爲了保證服務器7x24不宕機在線狀態,須要爲每臺單點服務器(由一臺服務器提供服務的服務器,如寫服務器、數據庫中間件)提供冗餘機。
對於寫服務器來講,須要提供一臺一樣的寫-冗餘服務器,當寫服務器健康時(寫-冗餘經過心跳檢測),寫-冗餘做爲一個從機的角色複製寫服務器的內容與其作一個同步;當寫服務器宕機時,寫-冗餘服務器便頂上來做爲寫服務器繼續提供服務。對外界來講這個處理過程是透明的,即外界僅經過一個IP訪問服務。
典型SQLDDL(Database Definition Language)是指數據庫表結構的定義(create table)和維護(alter table)的語言。在線上執行DDL,在低於MySQL5.6版本時會致使全表被獨佔鎖定,此時表處於維護、不可操做狀態,這會致使該期間對該表的全部訪問沒法響應。可是在MySQL5.6以後,支持Online DDL,大大縮短了鎖定時間。
優化技巧是採用的維護表結構的DDL(好比增長一列,或者增長一個索引),是==copy==策略。思路:建立一個知足新結構的新表,將舊錶數據==逐條==導入(複製)到新表中,以保證==一次性鎖定的內容少==(鎖定的是正在導入的數據),同時舊錶上能夠執行其餘任務。導入的過程當中,將對舊錶的全部操做以日誌的形式記錄下來,導入完畢後,將更新日誌在新表上再執行一遍(確保一致性)。最後,新表替換舊錶(在應用程序中完成,或者是數據庫的rename,視圖完成)。
但隨着MySQL的升級,這個問題幾乎淡化了。
在恢復數據時,可能會導入大量的數據。此時爲了快速導入,須要掌握一些技巧:
1
|
alter table table-name disable keys
|
待數據導入完成以後,再開啓索引和約束,一次性建立索引
1
|
alter table table-name enable keys
|
儘可能保證不要出現大的offset,好比limit 10000,10至關於對已查詢出來的行數棄掉前10000行後再取10行,徹底能夠加一些條件過濾一下(完成篩選),而不該該使用limit跳過已查詢到的數據。這是一個==offset作無用功==的問題。對應實際工程中,要避免出現大頁碼的狀況,儘可能引導用戶作條件過濾。
即儘可能選擇本身須要的字段select,但這個影響不是很大,由於網絡傳輸多了幾十上百字節也沒多少延時,而且如今流行的ORM框架都是用的select *,只是咱們在設計表的時候注意將大數據量的字段分離,好比商品詳情能夠單獨抽離出一張商品詳情表,這樣在查看商品簡略頁面時的加載速度就不會有影響了。
它的邏輯就是隨機排序(爲每條數據生成一個隨機數,而後根據隨機數大小進行排序)。如select * from student order by rand() limit 5的執行效率就很低,由於它爲表中的每條數據都生成隨機數並進行排序,而咱們只要前5條。
解決思路:在應用程序中,將隨機的主鍵生成好,去數據庫中利用主鍵檢索。
多表查詢:join、子查詢都是涉及到多表的查詢。若是你使用explain分析執行計劃你會發現多表查詢也是一個表一個表的處理,最後合併結果。所以能夠說單表查詢將計算壓力放在了應用程序上,而多表查詢將計算壓力放在了數據庫上。
如今有ORM框架幫咱們解決了單表查詢帶來的對象映射問題(查詢單表時,若是發現有外鍵自動再去查詢關聯表,是一個表一個表查的)。
在MyISAM存儲引擎中,會自動記錄表的行數,所以使用count(*)可以快速返回。而Innodb內部沒有這樣一個計數器,須要咱們手動統計記錄數量,解決思路就是單獨使用一張表:
id | table | count |
---|---|---|
1 | student | 100 |
若是能夠肯定僅僅檢索一條,建議加上limit 1,其實ORM框架幫咱們作到了這一點(查詢單條的操做都會自動加上limit 1)。
慢查詢日誌用於記錄執行時間超過某個臨界值的SQL日誌,用於快速定位慢查詢,爲咱們的優化作參考。
配置項: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
實操時應該從長時間設置到短的時間,即將最慢的SQL優化掉
一旦SQL超過了咱們設置的臨界時間就會被記錄到xxx-slow.log中
profile信息配置項:profiling
set profiling=on
開啓後,全部的SQL執行的詳細信息都會被自動記錄下來
1
2
3
4
5
6
7
8
9
10
|
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)
|
show profiles
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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',':)') |
+----------+------------+-------------------------------------------------------+
|
show profile for query Query_ID
上面show profiles的結果中,每一個SQL有一個Query_ID,能夠經過它查看執行該SQL通過了哪些步驟,各消耗了多場時間
典型的服務器配置如下的配置全都取決於實際的運行環境
max_connections,最大客戶端鏈接數
1
2
3
4
5
6
|
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 151 |
+-----------------+-------+
|
table_open_***,表文件句柄緩存(表數據是存儲在磁盤上的,緩存磁盤文件的句柄方便打開文件讀取數據)
1
2
3
4
5
6
|
mysql> show variables like 'table_open_***';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| table_open_*** | 2000 |
+------------------+-------+
|
key_buffer_size,索引緩存大小(將從磁盤上讀取的索引緩存到內存,能夠設置大一些,有利於快速檢索)
1
2
3
4
5
6
|
mysql> show variables like 'key_buffer_size';
+-----------------+---------+
| Variable_name | Value |
+-----------------+---------+
| key_buffer_size | 8388608 |
+-----------------+---------+
|
innodb_buffer_pool_size,Innodb存儲引擎緩存池大小(對於Innodb來講最重要的一個配置,若是全部的表用的都是Innodb,那麼甚至建議將該值設置到物理內存的80%,Innodb的不少性能提高如索引都是依靠這個)
1
2
3
4
5
6
|
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共享表空間)
安裝MySQL時附帶了一個壓力測試工具mysqlslap(位於bin目錄下)
1
2
3
4
5
6
7
8
|
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
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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
|
1
2
3
4
5
6
7
8
|
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
|
1
2
3
4
5
6
7
8
9
|
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
|
1
2
3
4
5
6
7
8
9
|
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
|