forked from kidgrow-microservices-platform

zhaoxiaohao
2021-02-26 42732fda8d3fdef36b33e2c46f2988df7424bf6a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.kidgrow.db.sharding;
 
import org.apache.commons.lang.StringUtils;
 
/**
 * 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
 *
 * @Description: 按照字符串Hash求余确定分表<br>
 * @Project: <br>
 * @CreateDate: Created in 2020/2/4 16:05 <br>
 * @Author: <a href="4345453@kidgrow.com">liuke</a>
 */
public class HashModTableSuffix implements TableSuffix {
 
    private String hash;
    private Long tableSize = 64L;
    private String tableSuffix="-000";
 
    public HashModTableSuffix(String hash,long tableSize, String tableSuffix) {
        if (StringUtils.isEmpty(hash)) {
            throw new IllegalArgumentException("hash should not be null or empty");
        }
        this.hash = hash;
        this.tableSize=tableSize;
        this.tableSuffix=tableSuffix;
    }
 
    @Override
    public String getSuffix() {
        String format = "%0" + (tableSuffix.length() - 1) + "d";
        return "_"+String.format(format, Math.abs(hash.hashCode()) % tableSize);
    }
}