1.ShardingSphere
2.集成项目为SpringCloud的项目
3.集成步骤
3.1. POM依赖引入
<!-- 数据库读写分离 -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.0.0</version>
</dependency>
3.2. 配置文件YAML
重点注意版本,不同版本的Sharding的配置属性差异很大
#数据源配置
spring:
# Sharding库配置
shardingsphere:
datasource:
names: master,slave1
# 数据源 主库; 负责写
master:
type: com.alibaba.druid.pool.DruidDataSource
url: ${数据库的url}
username: ${username}
password: ${password}
# 数据源 从库; 负责读
slave1:
type: com.alibaba.druid.pool.DruidDataSource
url: ${数据库的url}
username: ${username}
password: ${password}
# 读写分离
rules:
readwrite-splitting:
data-sources:
glapp:
write-data-source-name: master
read-data-source-names:
- slave1
load-balancer-name: roundRobin # 负载均衡算法名称
load-balancers:
roundRobin:
type: ROUND_ROBIN
props:
value: value
# 打印sql
props:
sql-show: true
3.3. 移除原先使用的数据源配置,将数据源托管给ShardingSphere
// 启动类上增加注解, 移除原先的单库链接数据源
@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class})
3.4. 启动项目查看日志
实现了主从库的读写分离,是不是贼简单!