在我《Spring Cloud微服務-全棧技術與案例解析》書中,第18章節分庫分表解決方案里有對Sharding-JDBC的使用進行詳細的講解。
之前是通過XML方式來配置數據源,讀寫分離策略,分庫分表策略等,之前有朋友也問過我,有沒有Spring Boot的方式來配置,既然已經用Spring Boot還用XML來配置感覺有點不協調。
其實吧我個人覺得只要能用,方便看,看的懂就行了,mybatis的SQL不也是寫在XML中嘛。
今天就給大家介紹下Spring Boot方式的使用,主要講解讀寫分離的配置,其余的后面再介紹。
所謂的Spring Boot方式就是直接可以通過屬性文件或者YAML文件來配置上面我們提到的那些信息。
主要還是用shardingjdbc提供的starter,配置如下:
<dependency>
<groupId>io.shardingjdbc</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>2.0.0.M3</version>
</dependency>
配置內容如下:
server.port=8084
mybatis.config-location=classpath:META-INF/mybatis-config.xml
sharding.jdbc.datasource.names=ds_master,ds_slave
# 主數據源
sharding.jdbc.datasource.ds_master.type=com.alibaba.druid.pool.DruidDataSource
sharding.jdbc.datasource.ds_master.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_master.url=jdbc:mysql://localhost:3306/ds_0?characterEncoding=utf-8
sharding.jdbc.datasource.ds_master.username=root
sharding.jdbc.datasource.ds_master.password=123456
# 從數據源
sharding.jdbc.datasource.ds_slave.type=com.alibaba.druid.pool.DruidDataSource
sharding.jdbc.datasource.ds_slave.driver-class-name=com.mysql.jdbc.Driver
sharding.jdbc.datasource.ds_slave.url=jdbc:mysql://localhost:3306/ds_1?characterEncoding=utf-8
sharding.jdbc.datasource.ds_slave.username=root
sharding.jdbc.datasource.ds_slave.password=123456
# 讀寫分離配置
sharding.jdbc.config.masterslave.load-balance-algorithm-type=round_robin
sharding.jdbc.config.masterslave.name=dataSource
sharding.jdbc.config.masterslave.master-data-source-name=ds_master
sharding.jdbc.config.masterslave.slave-data-source-names=ds_slave
-
sharding.jdbc.config.masterslave.load-balance-algorithm-type
查詢時的負載均衡算法,目前有2種算法,round_robin(輪詢)和random(隨機),算法接口是io.shardingjdbc.core.api.algorithm.masterslave.MasterSlaveLoadBalanceAlgorithm。實現類有RandomMasterSlaveLoadBalanceAlgorithm和RoundRobinMasterSlaveLoadBalanceAlgorithm。 -
sharding.jdbc.config.masterslave.master-data-source-name
主數據源名稱 -
sharding.jdbc.config.masterslave.slave-data-source-names
從數據源名稱,多個用逗號隔開
就是這么簡單,整個流程結束,下面就是寫代碼測試讀寫分離的效果了,我這邊用的mybatis,代碼在我的Github上,文章中就不貼出來了,大家都會。
參考代碼:https://github.com/yinjihuan/spring-cloud/tree/master/fangjia-sjdbc-read-write-springboot