zhanghua
2025-06-11 2ca169c85f61256fb5185c078dba1bfef2be5066
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
package cn.lili.common.utils;
 
import cn.lili.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
 
/**
 * SnowflakeInitiator
 *
 * @author Chopper
 * @version v1.0
 * 2022-01-14 14:04
 */
@Component
@Slf4j
public class SnowflakeInitiator {
 
    /**
     * 缓存前缀
     */
    private static final String KEY = "{Snowflake}";
 
    @Autowired
    private Cache cache;
 
    /**
     * 尝试初始化
     *
     * @return
     */
    @PostConstruct
    public void init() {
        Long num = cache.incr(KEY);
        long dataCenter = num / 32;
        long workedId = num % 32;
        //如果数据中心大于32,则抹除缓存,从头开始
        if (dataCenter >= 32) {
            cache.remove(KEY);
            num = cache.incr(KEY);
            dataCenter = num / 32;
            workedId = num % 32;
        }
        SnowFlake.initialize(workedId, dataCenter);
    }
 
    public static void main(String[] args) {
        SnowFlake.initialize(0, 8);
 
        System.out.println(SnowFlake.getId());
    }
}