赞
踩
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; } }
数据库中建了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
对应shardingsphere版本
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。