1、本文是在《在Docker上搭建MySQL主从复制-主库已有数据》一文的基础上写成的。
2、在pom.xml中引入依赖
<!--shardingsphere start-->
<!-- for spring boot -->
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<!-- for spring namespace -->
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>3.1.0</version>
</dependency>
<!--shardingsphere end-->
3、在application.yml中增加配置信息
在spring下增加allow-bean-definition-overriding,结果如下:
spring:
#读写分离需要如下配置,否则会报dataSource错误
main:
allow-bean-definition-overriding: true
以及sharding的相关配置:
#读写分离
sharding:
jdbc:
datasource:
names: master1,slave0,slave1
master1:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.1.108:5301/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true
username: root
password: xxx
slave0:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.1.108:5302/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true
username: root
password: xxx
slave1:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.1.108:5303/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true
username: root
password: xxx
# 配置读写分离
# 配置从库选择策略,提供轮询与随机,这里选择用轮询
config:
masterslave:
load-balance-algorithm-type: round_robin
name: ms
master-data-source-name: master1
slave-data-source-names: slave0,slave1
# 开启SQL显示,默认值: false,注意:仅配置读写分离时不会打印日志
props:
sql:
show: true
注:我当前的springboot版本为2.2.1,shardingsphere版本为3.1.0,如果启动时有空指针的情况,请检查相关版本信息是否一致。
结果如下:
最后修改于 2019-11-28 14:54:28
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

