liusheng
2025-12-26 2944ea778f0fc87c8e09ae47200d9de8069049e3
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
package com.ruoyi.project.common;
 
public class IdGeneratorUtils {
    // 时间戳左移的位数(22位给计数器)
    private static final long TIMESTAMP_SHIFT = 22;
    private static final long COUNTER_BITS = 22L;
    private static final long MAX_COUNTER = (1L << COUNTER_BITS) - 1;
 
    private static long lastTimestamp = -1L;
    private static long counter = 0L;
 
    public synchronized static long nextId() {
        long timestamp = System.currentTimeMillis();
 
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards");
        }
 
        if (timestamp == lastTimestamp) {
            counter = (counter + 1) & MAX_COUNTER;
            if (counter == 0) {
                // 同一毫秒内计数器用完,等待下一毫秒
                timestamp = waitNextMillis(lastTimestamp);
            }
        } else {
            counter = 0L;
        }
 
        lastTimestamp = timestamp;
 
        return ((timestamp) << TIMESTAMP_SHIFT) | counter;
    }
 
    private static long waitNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
 
}