Sharding-Jdbc實(shí)現(xiàn)讀寫分離、分庫(kù)分表,妙!
閱讀本文大概需要 15 分鐘。
來自:blog.csdn.net/qq_40378034/article/details/115264837
1、概覽

2、MySQL主從復(fù)制
1)、docker配置mysql主從復(fù)制
mkdir -p /usr/local/mysqlData/master/cnf
mkdir -p /usr/local/mysqlData/master/data
vim /usr/local/mysqlData/master/cnf/mysql.cnf
[mysqld]
## 設(shè)置server_id,注意要唯一
server-id=1
## 開啟binlog
log-bin=mysql-bin
## binlog緩存
binlog_cache_size=1M
## binlog格式(mixed、statement、row,默認(rèn)格式是statement)
binlog_format=mixed
docker run -itd -p 3306:3306 --name master -v /usr/local/mysqlData/master/cnf:/etc/mysql/conf.d -v /usr/local/mysqlData/master/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7
[root@aliyun /]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6af1df686fff mysql:5.7 "docker-entrypoint..." 5 seconds ago Up 4 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp master
[root@aliyun /]# docker exec -it master /bin/bash
root@41d795785db1:/# mysql -u root -p123456
mysql> GRANT REPLICATION SLAVE ON *.* to 'reader'@'%' identified by 'reader';
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
mkdir /usr/local/mysqlData/slave/cnf -p
mkdir /usr/local/mysqlData/slave/cnf -p
vim /usr/local/mysqlData/slave/cnf/mysql.cnf
[mysqld]
## 設(shè)置server_id,注意要唯一
server-id=2
## 開啟binlog,以備Slave作為其它Slave的Master時(shí)使用
log-bin=mysql-slave-bin
## relay_log配置中繼日志
relay_log=edu-mysql-relay-bin
## 如果需要同步函數(shù)或者存儲(chǔ)過程
log_bin_trust_function_creators=true
## binlog緩存
binlog_cache_size=1M
## binlog格式(mixed、statement、row,默認(rèn)格式是statement)
binlog_format=mixed
## 跳過主從復(fù)制中遇到的所有錯(cuò)誤或指定類型的錯(cuò)誤,避免slave端復(fù)制中斷
## 如:1062錯(cuò)誤是指一些主鍵重復(fù),1032錯(cuò)誤是因?yàn)橹鲝臄?shù)據(jù)庫(kù)數(shù)據(jù)不一致
slave_skip_errors=1062
docker run -itd -p 3307:3306 --name slaver -v /usr/local/mysqlData/slave/cnf:/etc/mysql/conf.d -v /usr/local/mysqlData/slave/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7
master_log_file、master_log_pos兩個(gè)參數(shù),然后切換到從服務(wù)器上進(jìn)行主服務(wù)器的連接信息的設(shè)置root@6af1df686fff:/# mysql -u root -p123456
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000003 | 591 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
[root@aliyun /]# docker inspect --format='{{.NetworkSettings.IPAddress}}' master
172.17.0.2
[root@aliyun /]# docker exec -it slaver /bin/bash
root@fe8b6fc2f1ca:/# mysql -u root -p123456
mysql> change master to master_host='172.17.0.2',master_user='reader',master_password='reader',master_log_file='mysql-bin.000003',master_log_pos=591;
mysql> start slave;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> show slave status\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 172.17.0.2
Master_User: reader
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000003
Read_Master_Log_Pos: 591
Relay_Log_File: edu-mysql-relay-bin.000002
Relay_Log_Pos: 320
Relay_Master_Log_File: mysql-bin.000003
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
2)、binlog和redo log回顧
Master Thread每一秒將redo log buffer刷新到redo log file 每個(gè)事務(wù)提交時(shí)會(huì)將redo log buffer刷新到redo log file 當(dāng)redo log緩沖池剩余空間小于1/2時(shí),會(huì)將redo log buffer刷新到redo log file

STATEMENT模式:binlog里面記錄的就是SQL語句的原文。優(yōu)點(diǎn)是并不需要記錄每一行的數(shù)據(jù)變化,減少了binlog日志量,節(jié)約IO,提高性能。缺點(diǎn)是在某些情況下會(huì)導(dǎo)致master-slave中的數(shù)據(jù)不一致 ROW模式:不記錄每條SQL語句的上下文信息,僅需記錄哪條數(shù)據(jù)被修改了,修改成什么樣了,解決了STATEMENT模式下出現(xiàn)master-slave中的數(shù)據(jù)不一致。缺點(diǎn)是會(huì)產(chǎn)生大量的日志,尤其是alter table的時(shí)候會(huì)讓日志暴漲 MIXED模式:以上兩種模式的混合使用,一般的復(fù)制使用STATEMENT模式保存binlog,對(duì)于STATEMENT模式無法復(fù)制的操作使用ROW模式保存binlog,MySQL會(huì)根據(jù)執(zhí)行的SQL語句選擇日志保存方式
redo log是InnoDB引擎特有的;binlog是MySQL的Server層實(shí)現(xiàn)的,所有引擎都可以使用 redo log是物理日志,記錄的是在某個(gè)數(shù)據(jù)也上做了什么修改;binlog是邏輯日志,記錄的是這個(gè)語句的原始邏輯,比如給ID=2這一行的c字段加1 redo log是循環(huán)寫的,空間固定會(huì)用完;binlog是可以追加寫入的,binlog文件寫到一定大小后會(huì)切換到下一個(gè),并不會(huì)覆蓋以前的日志
create table T(ID int primary key, c int);
update T set c=c+1 where ID=2;
執(zhí)行器先找到引擎取ID=2這一行。ID是主鍵,引擎直接用樹搜索找到這一行。如果ID=2這一行所在的數(shù)據(jù)也本來就在內(nèi)存中,就直接返回給執(zhí)行器;否則,需要先從磁盤讀入內(nèi)存,然后再返回 執(zhí)行器拿到引擎給的行數(shù)據(jù),把這個(gè)值加上1,得到新的一行數(shù)據(jù),再調(diào)用引擎接口寫入這行新數(shù)據(jù) 引擎將這行新數(shù)據(jù)更新到內(nèi)存中,同時(shí)將這個(gè)更新操作記錄到redo log里面,此時(shí)redo log處于prepare狀態(tài)。然后告知執(zhí)行器執(zhí)行完成了,隨時(shí)可以提交事務(wù) 執(zhí)行器生成這個(gè)操作的binlog,并把binlog寫入磁盤 執(zhí)行器調(diào)用引擎的提交事務(wù)接口,引擎把剛剛寫入的redo log改成提交狀態(tài),更新完成

3)、MySQL主從復(fù)制原理

在從庫(kù)B上通過change master命令,設(shè)置主庫(kù)A的IP、端口、用戶名、密碼,以及要從哪個(gè)位置開始請(qǐng)求binlog,這個(gè)位置包含文件名和日志偏移量 在從庫(kù)B上執(zhí)行start slave命令,這時(shí)從庫(kù)會(huì)啟動(dòng)兩個(gè)線程,就是圖中的I/O線程和SQL線程。其中I/O線程負(fù)責(zé)與主庫(kù)建立連接 主庫(kù)A校驗(yàn)完用戶名、密碼后,開始按照從庫(kù)B傳過來的位置,從本地讀取binlog,發(fā)給B 從庫(kù)B拿到binlog后,寫到本地文件,稱為中繼日志 SQL線程讀取中繼日志,解析出日志里的命令,并執(zhí)行
3、Sharding-Jdbc實(shí)現(xiàn)讀寫分離
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
spring.main.allow-bean-definition-overriding=true
#顯示sql
spring.shardingsphere.props.sql.show=true
#配置數(shù)據(jù)源
spring.shardingsphere.datasource.names=ds1,ds2,ds3
#master-ds1數(shù)據(jù)庫(kù)連接信息
spring.shardingsphere.datasource.ds1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds1.url=jdbc:mysql://47.101.58.187:3306/sharding-jdbc-db?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.shardingsphere.datasource.ds1.username=root
spring.shardingsphere.datasource.ds1.password=123456
spring.shardingsphere.datasource.ds1.maxPoolSize=100
spring.shardingsphere.datasource.ds1.minPoolSize=5
#slave-ds2數(shù)據(jù)庫(kù)連接信息
spring.shardingsphere.datasource.ds2.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds2.url=jdbc:mysql://47.101.58.187:3307/sharding-jdbc-db?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.shardingsphere.datasource.ds2.username=root
spring.shardingsphere.datasource.ds2.password=123456
spring.shardingsphere.datasource.ds2.maxPoolSize=100
spring.shardingsphere.datasource.ds2.minPoolSize=5
#slave-ds3數(shù)據(jù)庫(kù)連接信息
spring.shardingsphere.datasource.ds3.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds3.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds3.url=jdbc:mysql://47.101.58.187:3307/sharding-jdbc-db?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.shardingsphere.datasource.ds3.username=root
spring.shardingsphere.datasource.ds3.password=123456
spring.shardingsphere.datasource.ds.maxPoolSize=100
spring.shardingsphere.datasource.ds3.minPoolSize=5
#配置默認(rèn)數(shù)據(jù)源ds1 默認(rèn)數(shù)據(jù)源,主要用于寫
spring.shardingsphere.sharding.default-data-source-name=ds1
#配置主從名稱
spring.shardingsphere.masterslave.name=ms
#置主庫(kù)master,負(fù)責(zé)數(shù)據(jù)的寫入
spring.shardingsphere.masterslave.master-data-source-name=ds1
#配置從庫(kù)slave節(jié)點(diǎn)
spring.shardingsphere.masterslave.slave-data-source-names=ds2,ds3
#配置slave節(jié)點(diǎn)的負(fù)載均衡均衡策略,采用輪詢機(jī)制
spring.shardingsphere.masterslave.load-balance-algorithm-type=round_robin
#整合mybatis的配置
mybatis.type-aliases-package=com.ppdai.shardingjdbc.entity
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nickname` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`sex` int(11) DEFAULT NULL,
`birthday` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
@Data
public class User {
private Integer id;
private String nickname;
private String password;
private Integer sex;
private String birthday;
}
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@PostMapping("/save")
public String addUser() {
User user = new User();
user.setNickname("zhangsan" + new Random().nextInt());
user.setPassword("123456");
user.setSex(1);
user.setBirthday("1997-12-03");
userMapper.addUser(user);
return "success";
}
@GetMapping("/findUsers")
public List<User> findUsers() {
return userMapper.findUsers();
}
}
public interface UserMapper {
@Insert("insert into t_user(nickname,password,sex,birthday) values(#{nickname},#{password},#{sex},#{birthday})")
void addUser(User user);
@Select("select * from t_user")
List<User> findUsers();
}

http://localhost:8080/api/user/save一直進(jìn)入到ds1主節(jié)點(diǎn)
http://localhost:8080/api/user/findUsers一直進(jìn)入到ds2、ds3節(jié)點(diǎn),并且輪詢進(jìn)入
4、MySQL分庫(kù)分表原理
1)、分庫(kù)分表

2)、不停機(jī)分庫(kù)分表數(shù)據(jù)遷移
利用MySQL+Canal做增量數(shù)據(jù)同步,利用分庫(kù)分表中間件,將數(shù)據(jù)路由到對(duì)應(yīng)的新表中 利用分庫(kù)分表中間件,全量數(shù)據(jù)導(dǎo)入到對(duì)應(yīng)的新表中 通過單表數(shù)據(jù)和分庫(kù)分表數(shù)據(jù)兩兩比較,更新不匹配的數(shù)據(jù)到新表中 數(shù)據(jù)穩(wěn)定后,將單表的配置切換到分庫(kù)分表配置上

5、Sharding-Jdbc實(shí)現(xiàn)分庫(kù)分表
1)、邏輯表

#多數(shù)據(jù)源$->{0..N}.邏輯表名$->{0..N} 相同表
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds$->{0..1}.t_order$->{0..1}
#多數(shù)據(jù)源$->{0..N}.邏輯表名$->{0..N} 不同表
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds0.t_order$->{0..1},ds1.t_order$->{2..4}
#單數(shù)據(jù)源的配置方式
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds0.t_order$->{0..4}
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds0.t_order0,ds1.t_order0,ds0.t_order1,ds1.t_order1
2)、inline分片策略
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds$->{0..1}.t_order$->{0..1}
#數(shù)據(jù)源分片策略
spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.sharding-column=user_id
#數(shù)據(jù)源分片算法
spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.algorithm-expression=ds$->{user_id%2}
#表分片策略
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column=order_id
#表分片算法
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression=t_order$->{order_id%2}
insert into t_order(user_id,order_id) values(2,3),user_id%2 = 0使用數(shù)據(jù)源ds0,order_id%2 = 1使用t_order1,insert語句最終操作的是數(shù)據(jù)源ds0的t_order1表。3)、分布式主鍵配置
#主鍵的列名
spring.shardingsphere.sharding.tables.t_order.key-generator.column=id
#主鍵生成策略
spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE
4)、inline分片策略實(shí)現(xiàn)分庫(kù)分表
CREATE TABLE `t_user0` (
`id` bigint(20) DEFAULT NULL,
`nickname` varchar(200) DEFAULT NULL,
`password` varchar(200) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` int(11) DEFAULT NULL,
`birthday` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `t_user1` (
`id` bigint(20) DEFAULT NULL,
`nickname` varchar(200) DEFAULT NULL,
`password` varchar(200) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` int(11) DEFAULT NULL,
`birthday` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
spring.main.allow-bean-definition-overriding=true
#顯示sql
spring.shardingsphere.props.sql.show=true
#配置數(shù)據(jù)源
spring.shardingsphere.datasource.names=ds0,ds1
#ds0數(shù)據(jù)庫(kù)連接信息
spring.shardingsphere.datasource.ds0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds0.url=jdbc:mysql://47.101.58.187:3306/t_user_db0?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.shardingsphere.datasource.ds0.username=root
spring.shardingsphere.datasource.ds0.password=123456
spring.shardingsphere.datasource.ds0.maxPoolSize=100
spring.shardingsphere.datasource.ds0.minPoolSize=5
#ds1數(shù)據(jù)庫(kù)連接信息
spring.shardingsphere.datasource.ds1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.ds1.url=jdbc:mysql://47.101.58.187:3306/t_user_db1?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.shardingsphere.datasource.ds1.username=root
spring.shardingsphere.datasource.ds1.password=123456
spring.shardingsphere.datasource.ds1.maxPoolSize=100
spring.shardingsphere.datasource.ds1.minPoolSize=5
#整合mybatis的配置
mybatis.type-aliases-package=com.ppdai.shardingjdbc.entity
spring.shardingsphere.sharding.tables.t_user.actual-data-nodes=ds$->{0..1}.t_user$->{0..1}
#數(shù)據(jù)源分片策略
spring.shardingsphere.sharding.tables.t_user.database-strategy.inline.sharding-column=sex
#數(shù)據(jù)源分片算法
spring.shardingsphere.sharding.tables.t_user.database-strategy.inline.algorithm-expression=ds$->{sex%2}
#表分片策略
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.sharding-column=age
#表分片算法
spring.shardingsphere.sharding.tables.t_user.table-strategy.inline.algorithm-expression=t_user$->{age%2}
#主鍵的列名
spring.shardingsphere.sharding.tables.t_user.key-generator.column=id
spring.shardingsphere.sharding.tables.t_user.key-generator.type=SNOWFLAKE
@SpringBootTest
class ShardingJdbcApplicationTests {
@Autowired
private UserMapper userMapper;
/**
* sex:奇數(shù)
* age:奇數(shù)
* ds1.t_user1
*/
@Test
public void test01() {
User user = new User();
user.setNickname("zhangsan" + new Random().nextInt());
user.setPassword("123456");
user.setAge(17);
user.setSex(1);
user.setBirthday("1997-12-03");
userMapper.addUser(user);
}
/**
* sex:奇數(shù)
* age:偶數(shù)
* ds1.t_user0
*/
@Test
public void test02() {
User user = new User();
user.setNickname("zhangsan" + new Random().nextInt());
user.setPassword("123456");
user.setAge(18);
user.setSex(1);
user.setBirthday("1997-12-03");
userMapper.addUser(user);
}
/**
* sex:偶數(shù)
* age:奇數(shù)
* ds0.t_user1
*/
@Test
public void test03() {
User user = new User();
user.setNickname("zhangsan" + new Random().nextInt());
user.setPassword("123456");
user.setAge(17);
user.setSex(2);
user.setBirthday("1997-12-03");
userMapper.addUser(user);
}
/**
* sex:偶數(shù)
* age:偶數(shù)
* ds0.t_user0
*/
@Test
public void test04() {
User user = new User();
user.setNickname("zhangsan" + new Random().nextInt());
user.setPassword("123456");
user.setAge(18);
user.setSex(2);
user.setBirthday("1997-12-03");
userMapper.addUser(user);
}
}
https://shardingsphere.apache.org/document/current/cn/overview/
https://www.bilibili.com/video/BV1ei4y1K7dn
推薦閱讀:
官宣!字節(jié)跳動(dòng)取消大小周,員工卻高興不起來!內(nèi)網(wǎng)哀嚎:變相降薪20%,少賺一萬!
單點(diǎn)登錄解決方案?SpringSecurity結(jié)合JWT完美解決(附源碼)
最近面試BAT,整理一份面試資料《Java面試BATJ通關(guān)手冊(cè)》,覆蓋了Java核心技術(shù)、JVM、Java并發(fā)、SSM、微服務(wù)、數(shù)據(jù)庫(kù)、數(shù)據(jù)結(jié)構(gòu)等等。
朕已閱 
評(píng)論
圖片
表情

