ShardingSphere-JDBC基于MyBatis做MySQL主从读写分离
2021-10-26 17:44:08
## 引入依赖 pom.xml
```
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.0.0</version>
</dependency>
```
## 配置数据源
```
# 将之前的数据库配置信息注释掉
#spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
#spring.datasource.username=root
#spring.datasource.password=root
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#mybatis.configuration.map-underscore-to-camel-case=true
#mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 所有数据源名称
spring.shardingsphere.datasource.names=ds1,ds2,ds3
# 数据源1
spring.shardingsphere.datasource.ds1.jdbc-url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
spring.shardingsphere.datasource.ds1.username=root
spring.shardingsphere.datasource.ds1.password=root
spring.shardingsphere.datasource.ds1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源2
spring.shardingsphere.datasource.ds2.jdbc-url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
spring.shardingsphere.datasource.ds2.username=root
spring.shardingsphere.datasource.ds2.password=root
spring.shardingsphere.datasource.ds2.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds2.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源3
spring.shardingsphere.datasource.ds3.jdbc-url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
spring.shardingsphere.datasource.ds3.username=root
spring.shardingsphere.datasource.ds3.password=root
spring.shardingsphere.datasource.ds3.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds3.driver-class-name=com.mysql.cj.jdbc.Driver
# 负载均衡 ROUND_ROBIN/RANDOM
spring.shardingsphere.rules.readwrite-splitting.load-balancers.demo.type=ROUND_ROBIN
#spring.shardingsphere.rules.readwrite-splitting.load-balancers.demo.props.key1=val1
#spring.shardingsphere.rules.readwrite-splitting.load-balancers.demo.props.key2=val2
# 读写配置 ds1是主库,增删改走ds1,查询走ds2和ds3
spring.shardingsphere.rules.readwrite-splitting.data-sources.demo.load-balancer-name=demo
spring.shardingsphere.rules.readwrite-splitting.data-sources.demo.write-data-source-name=ds1
spring.shardingsphere.rules.readwrite-splitting.data-sources.demo.read-data-source-names=ds2,ds3
# 打印 sql
spring.shardingsphere.props.sql-show=true
```
可以看到,INSERT语句,使用ds1数据源,查询语句使用ds2、ds3。
![WX20211026-174526@2x.png](https://static.daimaku.net/post/202110/26/c84ebe706683c486a9c237f2d7e6b467.png)