1.使用Sharding-JDBC框架实现
1.1导入maven坐标
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
1.2配置读写分离的配置文件yml
spring:
shardingsphere:
datasource:
names: master,slave
#主数据源
master:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/rw?characterEncoding=utf-8
username: root
password:
#从数据源
slave:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://10.211.55.5:3306/rw?characterEncoding=utf-8
username: root
password: 123456
masterslave:
# 读写分离配置
load-balance-algorithm-type: round_robin # 从库负载均衡策略 轮询
# 最终的数据源名称
name: dataSource
# 主数据源名称
master-data-source-name: master
# 从数据源名称列表,使用逗号分割
slave-data-source-names: slave
props:
sql:
show: true #开启sql显示,默认是fasle
main:
allow-bean-definition-overriding: true # 允许bean定义覆盖