根据编码进行分表逻辑算法

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));
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容