duhuizhe
2023-10-16 3aa55dd3f62cee2c1c4c0aa74e1570acf83f8927
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.consum.base.core.util;
 
import com.consum.base.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.codec.Hex;
 
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 功能描述:获取随机值
 *
 * @author dhz
 * @date 2023-10-16 11:20
 * @Version 1.0
 **/
@Slf4j
public class RandomUtil {
 
    /**
     * 加盐字符串
     */
    private static final String SALT = "13";
 
    /**
     * 获取分组序号
     *
     * @param id    分组业务主键id
     * @param group 分组数 从0开始到 group-1 共group 组
     * @return 分组数
     */
    public static Integer getRandom(Long id, Integer group) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            byte[] digest = md5.digest((id + SALT).getBytes(StandardCharsets.UTF_8));
            char[] encode = Hex.encode(digest);
            Long parseLong = Long.parseLong(String.valueOf(encode).substring(0, 3), 16);
            return (int) (parseLong % group);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return -1;
    }
 
    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(2);
        Integer group = 13;
        long generateId = IdUtil.generateId();
        for (int i = 0; i < 10000; i++) {
            Integer random = RandomUtil.getRandom(generateId, group);
            if (map.containsKey(random)) {
                map.put(random, map.get(random) + 1);
            } else {
                map.put(random, 1);
            }
        }
        System.out.println(map);
    }
}