package com.*.*.utils;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
public class PartitionByMurmurHashUtil {
private static final int DEFAULT_VIRTUAL_BUCKET_TIMES = 160;
private static final int DEFAULT_WEIGHT = 1;
private int count;
private Map<Integer, Integer> weightMap = new HashMap<>();
private HashFunction hash;
private SortedMap<Integer, Integer> bucketMap;
public void init() {
try {
bucketMap = new TreeMap<>();
generateBucketMap();
} catch (Exception ignored) {
}
}
private void generateBucketMap() {
int seed = 0;
hash = Hashing.murmur3_32_fixed(seed);
for (int i = 0; i < count; i++) {
StringBuilder hashName = new StringBuilder("SHARD-").append(i);
for (int n = 0, shard = DEFAULT_VIRTUAL_BUCKET_TIMES * getWeight(i); n < shard; n++) {
bucketMap.put(hash.hashUnencodedChars(hashName.append("-NODE-").append(n)).asInt(), i);
}
}
weightMap = null;
}
private int getWeight(int bucket) {
Integer w = weightMap.get(bucket);
if (w == null) {
w = DEFAULT_WEIGHT;
}
return w;
}
public Integer calculate(String columnValue) {
SortedMap<Integer, Integer> tail = bucketMap.tailMap(hash.hashUnencodedChars(columnValue).asInt());
if (tail.isEmpty()) {
return bucketMap.get(bucketMap.firstKey());
}
return tail.get(tail.firstKey());
}
public static int hash(String code, Integer count) {
PartitionByMurmurHashUtil hash = new PartitionByMurmurHashUtil();
hash.count = count;
hash.init();
int h = hash.calculate(removeBackquote(code));
return ++h;
}
public static String removeBackquote(String str) {
if (str == null) {
return null;
}
str = str.trim();
if (str.length() >= 2) {
char firstChar = str.charAt(0);
int lastIndex = str.length() - 1;
char tailChar = str.charAt(lastIndex);
if ((firstChar == '`' && tailChar == '`') || (firstChar == '\'' && tailChar == '\'')) {
return str.substring(1, lastIndex);
}
}
return str;
}
public static void main(String[] args) {
System.out.println(hash("", 20));
}
}
根据编码进行分表逻辑算法
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 【蝴蝶效应】 蝴蝶效应:上个世纪70年代,美国一个名叫洛伦兹的气象学家在解释空气系统理论时说,亚马逊雨林一只蝴蝶...
- 一谈《道德与法治》课上的有效化活动教学 道德教育要回归生活,怎样让《道德与法治》教学提高实效性,达到育人目的...
- 华为近日清退了一批34岁以上的中年员工,都是程序员,原因很容易想得到,中年人精力和创造力方面弱很多,而稀少的管理岗...