雪花ID生成工具

public class SmallSnowflake {

    public static final int NODE_SHIFT = 10;
    public static final int SEQ_SHIFT  = 12;

    public static final short MAX_NODE     = 1023;
    public static final short MAX_SEQUENCE = 4095;

    private short sequence;
    private long  referenceTime;

    private int node;

   
    public SmallSnowflake(int node) {
        if (node < 0 || node > MAX_NODE) {
            throw new IllegalArgumentException(String.format("node must be between %s and %s", 0, MAX_NODE));
        }
        this.node = node;
    }

    
    public synchronized long next() {
        long currentTime = this.getCurrentTimeMillis();
        long counter;
        if (currentTime < referenceTime) {
            throw new RuntimeException(String.format("Last referenceTime %s is after reference time %s", referenceTime, currentTime));
        } else if (currentTime > referenceTime) {
            this.sequence = 0;
        } else {
            if (this.sequence < SmallSnowflake.MAX_SEQUENCE) {
                this.sequence++;
            } else {
                throw new RuntimeException("Sequence exhausted at " + this.sequence);
            }
        }
        counter = this.sequence;
        referenceTime = currentTime;

        return currentTime << NODE_SHIFT << SEQ_SHIFT | node << SEQ_SHIFT | counter;
    }

    protected long getCurrentTimeMillis() {
        return System.currentTimeMillis() / 1000;
    }


public class LargeSnowflake extends SmallSnowflake {

    public LargeSnowflake(int node) {
        super(node);
    }

    @Override
    protected long getCurrentTimeMillis() {
        return System.currentTimeMillis();
    }
}


   public static void main(String[] args) {
        LargeSnowflake lsf = new LargeSnowflake(1);
        System.out.println(lsf.next());
        SmallSnowflake ssf = new SmallSnowflake(1);
        System.out.println(ssf.next());
    }

 

雪花算法是一种分布式系统中生成唯一ID的算法,它可以生成一个64位的ID,其中包含了时间戳、机器ID和序列号等信息。下面是一个Java实现的雪花算法生成ID工具类: ```java public class SnowflakeIdGenerator { // 起始的时间戳 private final static long START_TIMESTAMP = 1609459200000L; //2021-01-01 00:00:00 // 每一部分占用的位数 private final static long SEQUENCE_BIT = 12; // 序列号占用的位数 private final static long MACHINE_BIT = 5; // 机器标识占用的位数 private final static long DATACENTER_BIT = 5; // 数据中心占用的位数 // 每一部分的最大值 private final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT); private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT); private final static long MAX_SEQUENCE_NUM = ~(-1L << SEQUENCE_BIT); // 每一部分向左的位移 private final static long MACHINE_LEFT = SEQUENCE_BIT; private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT; private final static long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT; private long datacenterId; // 数据中心ID private long machineId; // 机器ID private long sequence = 0L; // 序列号 private long lastTimestamp = -1L; // 上一次生成ID的时间戳 public SnowflakeIdGenerator(long datacenterId, long machineId) { if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) { throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0"); } if (machineId > MAX_MACHINE_NUM || machineId < 0) { throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0"); } this.datacenterId = datacenterId; this.machineId = machineId; } /** * 生成下一个唯一的ID * * @return Snowflake ID */ public synchronized long nextId() { long timestamp = System.currentTimeMillis(); // 时钟回拨,抛出异常 if (timestamp < lastTimestamp) { throw new RuntimeException("Clock moved backwards. Refusing to generate id"); } // 同一毫秒内生成ID if (lastTimestamp == timestamp) { sequence = (sequence + 1) & MAX_SEQUENCE_NUM; // 当前毫秒内的序列号已经达到最大值,等待下一毫秒再生成ID if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } // 不同毫秒内生成ID else { sequence = 0L; } lastTimestamp = timestamp; // 生成ID return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT) | (datacenterId << DATACENTER_LEFT) | (machineId << MACHINE_LEFT) | sequence; } /** * 等待下一个毫秒的到来 * * @param lastTimestamp 上一次生成ID的时间戳 * @return 当前毫秒的时间戳 */ private long tilNextMillis(long lastTimestamp) { long timestamp = System.currentTimeMillis(); while (timestamp <= lastTimestamp) { timestamp = System.currentTimeMillis(); } return timestamp; } } ``` 使用示例: ```java SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1); long id = idGenerator.nextId(); ``` 其中,`datacenterId`和`machineId`分别表示数据中心ID和机器ID,可以根据实际情况设置。`nextId()`方法用于生成下一个唯一的ID
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值