读写分离(Read-Write Splitting)是一种常见的数据库架构优化策略,通过将数据库的读操作(查询)和写操作(插入、更新、删除)分离到不同的数据库实例上,从而提高系统的性能、可扩展性和高可用性。
在项目中实现读写分离目前主流的实现技术是通过 Apache ShardingSphere 来实现数据库的读写分离的。
从 Apache ShardingSphere 官网也可以看出读写分离是其提供的主要功能之一:
ShardingSphere 官网地址:https://shardingsphere.apache.org/document/current/cn/features/readwrite-splitting/
通过 ShardingSphere 可以轻松实现 MySQL 数据库的读写分离,以下是基于最新 ShardingSphere 5.x 版本的实现步骤和关键代码:
ShardingSphere 通过 JDBC 驱动层透明代理实现读写分离,其核心逻辑为:
-- 主库配置(my.cnf)
server-id=1
log-bin=mysql-bin
binlog-format=ROW
-- 从库配置(my.cnf)
server-id=2
relay-log=relay-bin
read-only=1
-- 主库创建复制账号
CREATE USER 'repl'@'%' IDENTIFIED BY 'P@ssw0rd';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';
FLUSH PRIVILEGES;
-- 从库配置主库连接
CHANGE MASTER TO
MASTER_HOST='master_ip',
MASTER_USER='repl',
MASTER_PASSWORD='P@ssw0rd',
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=592;
START SLAVE;
1.添加 Maven 依赖
在 pom.xml 中添加 ShardingSphere 和数据库连接池的依赖:
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
2.配置 application.yml
在 application.yml 中配置数据源和读写分离规则:
spring:
shardingsphere:
datasource:
names: master,slave0
# 主库配置
master:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://master_ip:3306/db?useSSL=false
username: root
password: Master@123
# 从库配置
slave0:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://slave_ip:3306/db?useSSL=false
username: root
password: Slave@123
# 从库2配置
slave1:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://slave_ip:3306/db?useSSL=false
username: root
password: Slave@123
rules:
readwrite-splitting:
data-sources:
readwrite_ds:
type: Static
props:
write-data-source-name: master
read-data-source-names:
- slave0
- slave1
load-balancer-name: round_robin
load-balancers:
round_robin:
type: ROUND_ROBIN # 轮询
props:
sql-show: true # 显示实际路由的SQL
配置说明
3.验证读写分离
1.写操作测试
public void createUser(User user) {
userMapper.insert(user); // INSERT 语句自动路由到master
}
2.读操作测试
public List<User> listUsers() {
return userMapper.selectList(null); // SELECT 语句路由到slave0
}
3.查看执行日志
控制台会输出类似日志:
Actual SQL: master ::: INSERT INTO user (...)
Actual SQL: slave0 ::: SELECT * FROM user
HintManager.getInstance().setPrimaryRouteOnly();
spring:
shardingsphere:
rules:
readwrite-splitting:
data-sources:
readwrite_ds:
type: Dynamic
props:
auto-aware-data-source-name: readwrite_ds
health-check-enabled: true
health-check-max-retry-count: 3
health-check-retry-interval: 5000
主从延迟问题:异步复制场景下,刚写入的数据可能无法立即从从库读取,可通过 HintManager 强制读主库临时解决。
读写分离适用于以下场景:
读写分离是一种常见的数据库架构优化策略,通过将数据库的读操作和写操作分离,提高了系统的性能、可扩展性和高可用性。读写分离主流的实现技术是 Apache ShardingSphere,通过添加依赖,配置读写分离规则的方式就可以轻松的实现读写分离。