当前位置:   article > 正文

shardingsphere 自定义分片策略_shardingsphere自定义策略

shardingsphere自定义策略

1、编写自定义分片类 采用精确分片算法实现PreciseShardingAlgorithm

package com.spring.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Collection;

@Component
public class UserAlgorithm implements PreciseShardingAlgorithm<String> {


    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<String> preciseShardingValue) {
        if(!StringUtils.isEmpty(preciseShardingValue)){
            String shardingValue = preciseShardingValue.getValue();
            int index = getIndex(shardingValue);
            for(String name : tableNames){
                if(name.endsWith(index+"")){
                    return name;
                }
            }

        }

        return null;
    }


    private int getIndex(String uid){
        uid = uid.replace("-","");
        int res =  Math.abs(uid.hashCode())%10;
        return res;
    }
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

数据库中建了10张表 根据用户ID(为UUID)的hashcode 然后取模于 表的数量
doSharding(Collection tableNames, PreciseShardingValue preciseShardingValue) 参数说明:
tableNames 为当前所有的表名,preciseShardingValue 为当前分片字段的值

2、定义完后再配置文件中 指定下自定义配置的类文件(需要指定两个属性值)

#分片字段名称
spring.shardingsphere.sharding.tables.t_user.table-strategy.standard.sharding-column=user_id
分片策略自定义对应的类名
spring.shardingsphere.sharding.tables.t_user.table-strategy.standard.precise-algorithm-class-name=com.spring.config.UserAlgorithm

  • 1
  • 2
  • 3
  • 4
  • 5

对应shardingsphere版本

        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>4.0.0-RC1</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/756751
推荐阅读
相关标签
  

闽ICP备14008679号