ShardingSphere實現讀寫分離


在進行閱讀本文當中的內容之前首先你得要有主從復制的 MySQL 環境,可參考4.MySQL主從復制與分庫分表與讀取分離進行搭建

官方文檔:https://shardingsphere.apache.org/document/5.0.0-beta/cn/user-manual/shardingsphere-jdbc/configuration/spring-boot-starter/readwrite-splitting

然后我們在將 application.properties 替換成官方文檔當中給出的讀寫分離相關配置即可,配置項說明在官方文檔當中都說明了,博主就是將說明的內容替換成了真實的具體的內容,供參考即可:

image-20211219190241327

# 配置真實數據源
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 如果后面要做讀寫分離與分片的話可能就需要自行修改了,其它的就沒啥東西就在解釋的了:

image-20211219190433229

配置完畢之后,然后我們運行插入數據的測試代碼,運行結果如下:

image-20211219190556205

發現,都是往主庫當中進行寫的,那么就說明我們配置的讀寫分離已經生效了,然后我們在任意運行一個查詢語句看看它是否是去從庫當中進行查詢即可:

image-20211219190732201

發現,發送的 SQL 語句是去從,slave01 當中進行查詢了說明已經成功了,好了本文就到此結束了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM