1. 分區
- 一張表數據分成N個塊,在邏輯上看只是一張表,但底層由N個物理區塊組成
- 突破磁盤的讀寫能力,從而達到提高mysql性能的目的
- 特點
- 數據庫自身特性
- 無法跨庫,可跨存儲設備
- 數據庫自身保證數據完整性,一致性
- 缺點
- 分區數限制:1024
- 不支持外鍵
- mysql5開始支持分區
- mysql表由三個文件組成:.myd數據文件,.myi索引文件,.frm表結構文件
- 例
-
- TABLE `access_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`access_time` datetime NOT NULL,
PRIMARY KEY (`id`,`access_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
50100 PARTITION BY RANGE (to_days(access_time))
(PARTITION p1 VALUES LESS THAN (to_days(20190101)) ENGINE = InnoDB,
PARTITION p2 VALUES LESS THAN (to_days(20190102)) ENGINE = InnoDB,
PARTITION p3 VALUES LESS THAN (to_days(20190103)) ENGINE = InnoDB) ;
-- 新增分區
alter table access_log add partition(
partition p4 values less than (to_days('20190105'))
);
-- 刪除分區
alter table access_log drop partition p1;
-- 拆分分區
alter table access_log reorganize partition p4 into(
-> partition s0 values less than(to_days('20190104')),
-> partition s1 values less than(to_days('20190105'))
-> );
-- 合併分區
alter table access_log reorganize partition s0,s1 into (
partition p4 values less than (to_days('20190105'))
);
- TABLE `access_log` (
- 分區類型
- Range
- 連續區間
- List
- 枚舉值集合
- Hash
- 只能針對整數進行Hash
- 單列
- Key
- 多列
- Range
- 常見問題
- A PRIMARY KEY must include all columns in the table's partitioning function:這樣的話判斷主鍵是否唯一就可以在單個分區內部完成,否則就需要跨所有的分區
- MAXVALUE can only be used in last partition definition:RANGE表分區後不能帶MAXVALUE分區,否則無法增加分區。或者就只能重新分區了
- table access_log partition by range(to_days(access_time))(
partition p1 values less than (to_days('20191202')),
partition p2 values less than (to_days('20191203')),
partition po values less than (maxvalue)
)- Table has no partition for value 737425:因爲分區的範圍沒有包含所有可能的記錄的值
2. 分表
- 類型
- 水平分表
- 垂直分表
- 優點
- 單表併發提高,磁盤I/O性能提高,寫效率提高
- 訪問量大,且表數據比較大時,使用分表
- 缺點
- 需要業務處理,較複雜
- sharding-JDBC,MyCat
3. 分片(分庫)
- 場景
- 單臺DB存儲空間不足
- 高併發場景下,當數據庫Master無法承載寫操作壓力時,爲提高數據庫寫入能力
- 目的
- 突破單節點數據庫服務器的 I/O 能力限制,解決數據庫擴展性問題
- 拆分種類
- 水平分庫
- 將表數據拆分到不同的數據庫中
- 解決單表數據量增長出現的讀寫壓力
- 表結構相同
- 垂直分庫
- 按功能模塊拆分
- 解決表之間的IO競爭
- 水平分庫
- 要求
- 數據分佈均勻
- 負載均衡
- 數據遷移少
4. 分區與分片區別
- Scale Out - 橫向擴展,添加機器達到很好的擴展性
- Scale Up - 縱向擴展,添加更多的CPU,存儲設備,內存時達到很好擴展性