> 文章列表 > 【shardingsphere 5.x版本使用】,精准分表自定义策略配置,单库分表

【shardingsphere 5.x版本使用】,精准分表自定义策略配置,单库分表

【shardingsphere 5.x版本使用】,精准分表自定义策略配置,单库分表

之前有发过4.x版本的使用教程,这次项目升级了5.x版本,教程实战贴一下

1. 首先是maven依赖的添加

        <!-- Sharding-JDBC --><dependency><groupId>org.apache.shardingsphere</groupId><artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId><version>5.1.2</version></dependency>

2. yaml的配置,只配置一个数据库,单库分表,使用精准自定义分片策略

5.1.2版本增加一个参数props,将分片策略和全限定类名配置在这个下面。
而且精准分片的接口StandardShardingAlgorithm实现类需要实现的方法也多了两个,getProps和

@Overridepublic String doSharding(Collection<T> tableNames, PreciseShardingValue<T> preciseShardingValue) {return null;}@Overridepublic Collection<String> doSharding(Collection<T> collection, RangeShardingValue<T> rangeShardingValue) {return null;}@Overridepublic String getType() {return null;}// 新增方法,暂不知用处@Overridepublic Properties getProps() {return null;}// 新增方法 删除了原init();方法,多了个参数properties@Overridepublic void init(Properties properties) {}
spring:main:allow-bean-definition-overriding: trueshardingsphere:# 是否启用 Shardingenabled: true# 打印sqlprops:sql-show: truedatasource:names: mastermaster:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8username: rootpassword: rootrules:sharding:# 表策略配置tables:# terminal_heartbeat 是逻辑表terminal_heartbeat:actualDataNodes: master.tableStrategy:# 使用标准分片策略standard:# 配置分片字段shardingColumn: terminal_code# 分片算法名称,不支持大写字母和下划线,否则启动就会报错shardingAlgorithmName: time-sharding-altorithm# 分片算法配置shardingAlgorithms:# 分片算法名称,不支持大写字母和下划线,否则启动就会报错time-sharding-altorithm:# 类型:自定义策略type: CLASS_BASEDprops:# 分片策略strategy: standard# 分片算法类algorithmClassName: com..ShardingAlgorithmA

3. 踩坑合集:

  1. ShardingJDBC 5.1.0使用druid连接池需要加dbcp依赖
<dependency><groupId>org.apache.tomcat</groupId><artifactId>tomcat-dbcp</artifactId><version>10.0.16</version>
</dependency>
  1. 与flyway一起使用时会报错,因为flyway会查询 information_schema.schemata 用户权限和数据库表集合等信息,而ShardingJDBC暂未支持
    官方回复5.1.1已支持pr地址:https://github.com/apache/shardingsphere/issues/16234

但是我已尝试还是无效,会报错org.apache.shardingsphere.infra.exception.SchemaNotExistedException: Schema ‘information_schema’ 不存在

解决方法:使用Sharding-proxy,或者禁用flyway