ShardingSphere实现读写分离
在进行阅读本文当中的内容之前首先你得要有主从复制的 MySQL 环境,可参考4.MySQL主从复制与分库分表与读取分离进行搭建
然后我们在将 application.properties 替换成官方文档当中给出的读写分离相关配置即可,配置项说明在官方文档当中都说明了,博主就是将说明的内容替换成了真实的具体的内容,供参考即可:
# 配置真实数据源
spring.shardingsphere.datasource.names=master,slave01
# 配置第 1 个数据源
spring.shardingsphere.datasource.master.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.master.url=jdbc:mysql://180.96.127.246:3307/test?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.master.username=root
spring.shardingsphere.datasource.master.password=root
# 配置第 2 个数据源
spring.shardingsphere.datasource.slave01.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.slave01.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.slave01.url=jdbc:mysql://121.5.121.166:3308/test?serverTimezone=GMT%2B8
spring.shardingsphere.datasource.slave01.username=root
spring.shardingsphere.datasource.slave01.password=root
# 主键生成策略
spring.shardingsphere.rules.readwrite-splitting.data-sources.pr_ds.write-data-source-name=master
spring.shardingsphere.rules.readwrite-splitting.data-sources.pr_ds.read-data-source-names=slave01
spring.shardingsphere.rules.readwrite-splitting.data-sources.pr_ds.load-balancer-name=round-robin
spring.shardingsphere.rules.readwrite-splitting.load-balancers.round-robin.type=ROUND_ROBIN
# 打印执行sql
spring.shardingsphere.props.sql-show=true
如上配置文件当中的负载均衡算法博主采用的是官方当中内置提供的,可配置属性官方当中给出的可以是无,所以博主这里去掉了,readwrite-splitting-data-source-name
可以先使用内置的也就是 pr_ds
如果后面要做读写分离与分片的话可能就需要自行修改了,其它的就没啥东西就在解释的了:
配置完毕之后,然后我们运行插入数据的测试代码,运行结果如下:
发现,都是往主库当中进行写的,那么就说明我们配置的读写分离已经生效了,然后我们在任意运行一个查询语句看看它是否是去从库当中进行查询即可:
发现,发送的 SQL 语句是去从,slave01 当中进行查询了说明已经成功了,好了本文就到此结束了。