Pu Zhibing
2025-02-19 8f45afced0c6a4085560c62dbd58e6ef0f4cecf4
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.ruoyi.web.tool;
 
 
/**
 * id生成器
 */
public class IDUtil {
    /**
     * 存储时间戳
     */
    private static long timestamp = System.currentTimeMillis();
    /**
     * 自增长值
     */
    private static int self = 0;
    /**
     * 最大自增长值
     */
    private static int max_self = 9999;
    /**
     * 设备号
     */
    private static int device = 0;
    /**
     * 时针回拨增长值
     */
    private static int hour_hand_variable = 0;
    /**
     * 时针回拨最大增长值
     */
    private static int max_hour_hand_variable = 999;
 
 
    /**
     * 时间戳id
     * @return
     */
    public static long timestamp_id(){
        return timestamp;
    }
 
    /**
     * 生成唯一ID
     * @return
     */
    public static long sole_id(){
        return sole_id(null);
    }
 
 
    /**
     * 唯一ID生成
     * @param workId    工作ID
     * @return
     */
    public synchronized static long sole_id(Integer workId){
        if(null != workId){
            device = workId;
        }
        long timeMillis = System.currentTimeMillis();
        /**
         * 时间戳相同
         * 自增长值使用完后,休眠等待时间戳更新
         */
        if(timeMillis == timestamp && self > max_self){
            try {
                Thread.sleep(1);
                self = 0;
                return sole_id(workId);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        //处理时针回拨的情况
        if(timeMillis < timestamp) {
            if (hour_hand_variable >= max_hour_hand_variable) {
                hour_hand_variable = 0;
            } else {
                hour_hand_variable++;
            }
        }
        //处理
        if(timeMillis > timestamp){
            timestamp = timeMillis;
            self = 0;
        }
        return splice();
    }
 
 
    /**
     * 拼接最终的id
     * @return
     */
    private static long splice(){
        //格式化自增长数据格式,前位补0
        String format = String.format("%04d", self);
        Long id = Long.valueOf(timestamp + "" + hour_hand_variable + "" + device + format);
        self++;
        return id;
    }
}