sharding-jdbc分库分表开发包
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
按月分表规则
public class USerTablePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date>{
@Override
public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> preciseShardingValue) {
StringBuffer tableName = new StringBuffer();
tableName.append(preciseShardingValue.getLogicTableName())
.append("_").append(DateUtil.date2Str(preciseShardingValue.getValue(), DateUtil.YEAR_MONTH_NUMBER));
return tableName.toString();
}
}
测试按月分表规则
properties文件中添加配置项
sharding.jdbc.data-source.names=test0
sharding.jdbc.data-source.test0.type=com.zaxxer.hikari.HikariDataSource
sharding.jdbc.data-source.test0.driver-class-name=com.mysql.cj.jdbc.Driver
sharding.jdbc.data-source.test0.jdbc-url=jdbc:mysql://localhost:3306/test0?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
sharding.jdbc.data-source.test0.username=root
sharding.jdbc.data-source.test0.password=111111
# 水平拆分的数据库(表) 配置分库 + 分表策略 行表达式分片策略
# 分库策略
sharding.jdbc.config.sharding.default-data-source-name=test0
sharding.jdbc.config.sharding.tables.t_user.table-strategy.standard.sharding-column=create_time
sharding.jdbc.config.sharding.tables.t_user.table-strategy.standard.precise-algorithm-class-name=com.example.sharding.demo.config.UserTableShardingAlgorithm
# 打印执行的数据库以及语句 默认值: false,注意:仅配置读写分离时不会打印日志!!!
sharding.jdbc.data-source.props.sql.show=true
sharding.jdbc.config.props.sql.show=true
测试结果