1、相关的依赖如下
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.1.2</version>
</dependency>
2、相关配置如下
spring:
shardingsphere:
datasource:
names: m0,s0
m0:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.182.128:3306/user_db?serverTimezone=Asia/Shanghai
username: root
password: 123456
s0:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.182.128:3307/user_db?serverTimezone=Asia/Shanghai
username: root
password: 123456
rules:
readwrite-splitting:
data-sources:
readwrite_ds: #定义读写分离数据源
type: Static
props:
write-data-source-name: m0
read-data-source-names: s0
sharding:
tables:
t_user:
actual-data-nodes: readwrite_ds.t_user #声明读写分离数据源中的表
props:
sql-show: true
main:
allow-bean-definition-overriding: true
基于MySQL主从复制实现,其中m0是mysql的主库数据源,s0是mysql的从库数据源,具体配置一定要根据shardingjdbc的版本来写,不同的版本差异很大,查看官方文档一旦选错了版本,运行出现问题,很难发现错在哪里,浪费了很多时间!