java 实现雪花算法

2023-03-25 13:44:53 浏览数 (1)

代码语言:javascript复制
public class SnowflakeIdGenerator {
    
    private final static long START_TIMESTAMP = 1609528800000L; // 2021-01-01 00:00:00
    private final static long WORKER_ID_BITS = 5L;
    private final static long DATACENTER_ID_BITS = 5L;
    private final static long SEQUENCE_BITS = 12L;
    
    private final static long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private final static long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);
    
    private final static long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private final static long DATACENTER_ID_SHIFT = SEQUENCE_BITS   WORKER_ID_BITS;
    private final static long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS   WORKER_ID_BITS   DATACENTER_ID_BITS;
    
    private final static long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
    
    private long workerId;
    private long datacenterId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;
    
    public SnowflakeIdGenerator(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID can't be greater than "   MAX_WORKER_ID   " or less than 0");
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID can't be greater than "   MAX_DATACENTER_ID   " or less than 0");
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }
    
    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id for "   (lastTimestamp - timestamp)   " milliseconds");
        }
        if (timestamp == lastTimestamp) {
            sequence = (sequence   1) & SEQUENCE_MASK;
            if (sequence == 0L) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        
        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT) |
            (datacenterId << DATACENTER_ID_SHIFT) |
            (workerId << WORKER_ID_SHIFT) |
            sequence;
    }
    
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}

使用方式:

代码语言:javascript复制
java复制代码SnowflakeIdGeneratoridGenerator=newSnowflakeIdGenerator(workerId, datacenterId);
longid= idGenerator.nextId();

其中workerId和datacenterId是分别代表工作机器ID和数据中心ID,需要在不同的机器上设置不同的值。

0 人点赞