分表工具类(根据唯一字符串)

 

分表工具:

@Data
public class TableNumUtil {

    public static BigDecimal getTableNum(String str, Integer tableTotle) {
        
        if(StringUtils.isEmpty(str) || null == tableTotle) {
            return null;
        }
        
        BigDecimal data = null;
        try {
            //MessageDigest 类为应用程序提供信息摘要算法的功能,如 MD5 或 SHA 算法。
            //信息摘要是安全的单向哈希函数,它接收 任意大小的数据,并输出固定长度的哈希值。
            //MessageDigest 对象开始被初始化。
            MessageDigest mDigest = MessageDigest.getInstance("MD5");
            //通过使用 update 方法处理数据
            mDigest.update(str.getBytes());
            // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
            String hexString = new BigInteger(1, mDigest.digest()).toString(10);
            
            System.out.println(hexString);
            data = new BigDecimal(hexString).divideAndRemainder(new BigDecimal(tableTotle.toString()))[1];
            
            
            
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return data;
    }
}

 

posted @ 2020-07-10 17:31  乌瑟尔  阅读(359)  评论(0编辑  收藏  举报