话不多说先上pom依赖
<!-- 分库分表 -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>4.0.0-RC1</version>
在实际开发中,如果表的数据过大,我们可能需要把一张表拆分成多张表,这里就是通过ShardingSphere实现分表功能,但不分库
application.properties
# 数据源 saas
spring.shardingsphere.datasource.names=saas
#spring.datasource.url=jdbc:mysql://192.168.2.212:3306/saas?useUnicode=true&characterEncoding=utf8
#spring.datasource.username=root
#spring.datasource.password=root
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 第一个数据库
spring.shardingsphere.datasource.saas.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.saas.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.saas.jdbc-url=jdbc:mysql://192.168.2.212:3306/saas?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&verifyServerCertificate=false&autoReconnct=true&autoReconnectForPools=true&allowMultiQueries=true
spring.shardingsphere.datasource.saas.username=root
spring.shardingsphere.datasource.saas.password=root
#数据分表规则
#指定所需分的表
spring.shardingsphere.sharding.tables.wx_pay_log.actual-data-nodes=saas.wx_pay_log$->{0..5}
#指定主键
spring.shardingsphere.sharding.tables.wx_pay_log.table-strategy.inline.sharding-column=id
#分表规则为主键除以6取模
spring.shardingsphere.sharding.tables.wx_pay_log.table-strategy.inline.algorithm-expression=wx_pay_log$->{id % 6}
# 使用SNOWFLAKE算法生成主键
spring.shardingsphere.sharding.tables.wx_pay_log.key-generator.column = id
spring.shardingsphere.sharding.tables.wx_pay_log.key-generator.type = SNOWFLAKE
#打印sql
spring.shardingsphere.props.sql.show=true
测试
@Slf4j
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/test")
public class test {
@Autowired
private PayLogService payLogService;
@Autowired
private IdWorker idWorker;
@RequestMapping(value = "/test1")
public String test() {
PayLog payLog = new PayLog();
for (int i = 0; i < 50; i++) {
payLog.setId(idWorker.nextId());
payLog.setBody("666");
payLog.setLateFee(2);
payLog.setOrderNum("1231651321651");
payLogService.insertPayLog(payLog);
}
return "执行完毕";
}
@RequestMapping(value = "/find")
public List<PayLog> findAll(){
List<PayLog> allPayLog = payLogService.findAllPayLog();
return allPayLog;
}
}
Mysql 我用了6张表
总结
遇到不能分表的情况,只有一个原因.就是配置文件的问题.仔细检查检查.