com.github.antelopeframework.mybatis.shard.routing.PartitionRouter Maven / Gradle / Ivy
package com.github.antelopeframework.mybatis.shard.routing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.Setter;
/**
* 数据库分区路由.
*
* @author yangzhi.yzh
*
*/
public class PartitionRouter implements InitializingBean {
private Map groupMapping = new HashMap<>();
@Setter
@Autowired
List partitionGroups = new ArrayList<>();
@Override
public void afterPropertiesSet() throws Exception {
if (partitionGroups != null) {
for (PartitionGroup p : partitionGroups) {
groupMapping.put(p.getName(), p);
}
}
}
/**
* 根据pValue (对应 PartitionGroup中的name
属性), 获取到最终的分区名称.
*
* @param pValue
* @return
*/
public String getFinalPartitionKey(String pValue) {
PartitionGroup pGroup = groupMapping.get(pValue);
if (pGroup == null) {
throw new IllegalArgumentException("no PartitionGroup with name: " + pValue);
}
return buildFinalShardKey(pGroup.getName(), 0);
}
/**
* 根据pValue (对应 PartitionGroup中的name
属性) 以及 分表参考值, 获取到最终的分区名称.
* 使用的算法为: Math.abs(shardValue.hashCode() % pGroup.size())
.
*
* @param pValue
* @param shardValue 分表参考值
* @return
*/
public String getFinalShardKey(String pValue, Object shardValue) {
PartitionGroup pGroup = groupMapping.get(pValue);
if (pGroup == null) {
throw new IllegalArgumentException("no PartitionGroup with name: " + pValue);
}
return buildFinalShardKey(pGroup.getName(), Math.abs(shardValue.hashCode()) % pGroup.size());
}
/**
* 获取所有的 {@link PartitionGroup}.
*
* @return
*/
public List getPartitionGroups() {
return Collections.unmodifiableList(partitionGroups);
}
/**
*
* @param pName {@link PartitionGroup} 的 name
属性.
* @param shardIndex
* @return
*/
public static String buildFinalShardKey(String pName, int shardIndex) {
return pName + "::" + shardIndex;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy