标签:重写 databases sys toms lang gtest jdbc ret cti
首先创建简单maven项目,这里不做说明,自己搞
导入依赖
<!-- sharding-jdbc依赖 --> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>4.0.0-RC1</version> </dependency>
创建自定义的方法,需要实现 ShardingAlgorithm接口或者这个接口的子类,并重写里面的方法(就一个),下面是我的类中的全部代码,根据需要自己改
package com; import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm; import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static java.lang.System.out; /** * @author :zhangyantao * @date : 2020/6/9 18:20 **/ public class CustomShardingTest implements PreciseShardingAlgorithm<String> { /** * 数据库前缀 */ private static final String PREFIX = "ds_"; /** * 自定义库名配置 */ private static Map<String, String> map = new HashMap<String, String>(); static { map.put("420216", "370201"); } /** * availableTargetNames 被查到的库列表 * preciseShardingValue 分片列的值 */ @Override public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> preciseShardingValue) { if (preciseShardingValue != null) { out.println("availableTargetNames:"+availableTargetNames.toString()); out.println("preciseShardingValue:"+preciseShardingValue.toString()); String value = preciseShardingValue.getValue(); for (String name : availableTargetNames) { out.println("value:"+value); if (null != map.get(value) && map.get(value).trim().length() > 0) { //特定分片值处理 value = map.get(value); } String newName = PREFIX + Integer.parseInt(value) / 10000; out.println("name:"+name); out.println("newName:"+newName); if (newName.equals(name)) { return name; } } throw new UnsupportedOperationException("没有匹配到可用库"); } else { throw new UnsupportedOperationException("分片列为空"); } } }
写完之后把整个项目打成jar包,然后把jar包导入到sharding proxy解压目录下的 lib ,然后在分库或分表的分片算法位置使用
databaseStrategy:
standard:
shardingColumn: STR_AREA_CODE
preciseAlgorithmClassName: com.CustomShardingTest
在preciseAlgorithmClassName处调用jar包内的类路径,jar包放在lib下面,启动时自动加载。
物理库自行创建,必须有分片列,其他随意。
sharding proxy自定义分片规则 standard算法 preciseAlgorithmClassName属性
标签:重写 databases sys toms lang gtest jdbc ret cti
原文地址:https://www.cnblogs.com/of-course/p/13084934.html