实现案例springboot+mybatis-plus+shardingJdbc5
1.准备工作,springboot+mybatis-plus工程,创建两个数据库,各包含t_pro_area,t_pro_fram两张表,字段随意
2.引入shardingjdbc jar
<!-- 分库分表 -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.1.2</version>
</dependency>
3.yml文件配置
spring:
shardingsphere:
props:
# 日志显示具体的SQL
sql-show: false
# 是否开启
datasource:
# 数据源(逻辑名字)
names: ds0,ds1
# 配置数据源
ds0:
type: com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.cj.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/fishery-1?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimeZone=GMT%2B8&allowPublicKeyRetrieval=true
username: root
password: 123456
ds1:
type: com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.cj.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/fishery-2?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimeZone=GMT%2B8&allowPublicKeyRetrieval=true
username: root
password: 123456
# 分片的配置
rules:
sharding:
# 表的分片策略
tables:
# 逻辑表的名称
t_pro_fram:
# 数据节点配置,采用Groovy表达式
actual-data-nodes: ds$->{0..1}.t_pro_fram
# 配置策略
database-strategy: #分库策略
standard:
sharding-column: sort # 分片列名称
sharding-algorithm-name: user_inline # 分片算法名称
# table-strategy: #分表策略
# standard:
# sharding-column: sort
# sharding-algorithm-name: database_alg
#分片算法名
sharding-algorithms:
user_inline:
type: inline
props:
algorithm-expression: ds$->{sort % 2}
测试controller
@RestController
@RequestMapping("test")
public class tController {
@Autowired
private ProFarmService proFarmService;
@GetMapping("/list")
public String list() {
for (int i = 1 ; i < 10; i++) {
ProFarm test =new ProFarm();
test.setCusNo("嗡嗡嗡"+i);
test.setSort(i);
proFarmService.save(test);
}
retun "seccess";
}
}
规则ds$->{so