实现案例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:# 日志显示具体的SQLsql-show: false# 是否开启datasource:# 数据源(逻辑名字)names: ds0,ds1# 配置数据源ds0:type: com.zaxxer.hikari.HikariDataSourcedriverClassName: com.mysql.cj.jdbc.DriverjdbcUrl: jdbc:mysql://localhost:3306/fishery-1?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimeZone=GMT%2B8&allowPublicKeyRetrieval=trueusername: rootpassword: 123456ds1:type: com.zaxxer.hikari.HikariDataSourcedriverClassName: com.mysql.cj.jdbc.DriverjdbcUrl: jdbc:mysql://localhost:3306/fishery-2?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimeZone=GMT%2B8&allowPublicKeyRetrieval=trueusername: rootpassword: 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: inlineprops:algorithm-expression: ds$->{sort % 2}
测试controller
@RestController@RequestMapping("test")public class tController { @Autowiredprivate 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$->