Skip to content

sharding-jdbc自定义算法

一、介绍

sharding-jdbc4.x和5.x版本的分片算法使用不一样,在ShardingJdbc 5.x版本中,已经去除了分片策略的yml配置方式,改用SPI方式进行分片策略的注入了, 所以之前4.x版本时的分片方法已经不实用了

https://shardingsphere.apache.org/document/legacy/4.x/document/cn/overview/

二、x版本

2.1 自定义算法类

实现ComplexKeysShardingAlgorithm 接口

java
public class CustomizeAlgorithm implements ComplexKeysShardingAlgorithm {
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, Collection<ShardingValue> shardingValues) {
    }
}

2.2 yml配置文件

yaml
spring:
  sharding:
    tables:
      customer_order:
        actual-data-nodes: master.customer_order_$->{0..2}
        table-strategy:
          complex:
            algorithm-class-name: com.lcy.concurrency.CustomizeAlgorithm
            sharding-columns: code

三、x版本

3.1 自定义算法类

实现StandardShardingAlgorithm接口

java
public class CustomizeAlgorithm  implements StandardShardingAlgorithm<String> {
    @Override public String doSharding(Collection<String> collection,PreciseShardingValue<String> preciseShardingValue){
        //返回需要具体操作的库或表名
        return null;
    }

    @Override public Collection<String> doSharding(Collection<String> collection,RangeShardingValue<String> rangeShardingValue){
        return null;
    }

    @Override public Properties getProps() {
        return null;
    }

    @Override public void init(Properties properties){
    }

    @Override public String getType() {
        //这个为算法的类型
        return "customize";
    }
}

3.2 创建静态策略配置文件

在 resource 文件夹下创建 META-INF/services文件夹,并在该文件夹下创建org.apache.shardingsphere.sharding.spi.ShardingAlgorithm文件,将自定义的类加入其中,如下:

com.lcy.concurrency.CustomizeAlgorithm

3.3 yml配置文件

yml配置文件如下:

yaml
spring:
  shardingsphere:
    rules:
      tables:
        t_order:
          actual-data-nodes: ds.t_order_$->{202201..203012}
          table-strategy:
            standard:
              sharding-algorithm-name: order-algorithms
              sharding-column: code
    sharding:
      sharding-algorithms:
        order-algorithms:
          #这里的类型对应自定义算法的type
          type: customize