根据雪花算法生成带时间戳的全局唯一ID


import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 根据虚化算法改造,生成带时间戳的全局唯一ID
 * 仅适用于机器IP后缀不同使用
 * 无关机房,IP地址尾号一样的不适用,可能会出现重复ID问题
 *
 *
 * @Author: ylj
 * @Date: 2023/11/20
 */
@Slf4j
public class UniqueIdUtils {

    /**
     * 代表每毫秒内可产生最大序列号,即9999
     */
    private static final int MAX_SEQ = 9999;
    /**
     * 序列号初始值
     */
    private static long sequence = 10;
    /**
     * 初始化机器码,区分不通机器
     * 
     */
    private static String WORK_ID = "00";
    /**
     * 记录最后使用的毫秒时间戳,主要用于判断是否同一毫秒
     */
    private long lastTimeMillis = -1L;

    /**
     * 初始化
     */
    static {
        try {
            String ip = getIp();
            WORK_ID = ip.substring(ip.lastIndexOf(".") + 1);
        } catch (UnknownHostException e) {
            log.warn("unknown host exception:{}", e.getMessage());
        }
    }

    /**
     * 生成全局唯一ID
     * @return
     */
    public synchronized String nextId(){
        // 获取当前时间戳,单位为毫秒
        long currentTimeMillis  = System.currentTimeMillis();
        // 当前时间小于上一次生成id使用的时间,可能出现服务器时钟回拨问题
        if (currentTimeMillis < lastTimeMillis) {
            throw new RuntimeException(
                    String.format("可能出现服务器时钟回拨问题,请检查服务器时间。当前服务器时间戳:%d,上一次使用时间戳:%d",
                            currentTimeMillis, lastTimeMillis));
        }
        if (lastTimeMillis == currentTimeMillis) {
            sequence = sequence + 1;
            //如果序号到达最大值,获取下一毫秒时间的序号值
            if (sequence == MAX_SEQ){
                currentTimeMillis  = tilNextMillis(lastTimeMillis);
                //重置序号
                sequence = 10;
            }
        }else{
            //重置序号
            sequence = 10;
        }
        StringBuffer sb = new StringBuffer();
        sb.append(WORK_ID).append(currentTimeMillis).append(sequence);
        lastTimeMillis = currentTimeMillis;
        return sb.toString();
    }

    private static long tilNextMillis(long lastTimestamp) {
        // 获取当前时间戳,单位为毫秒
        long timestamp = timeGen();
        // 如果当前时间戳小于等于上一个生成ID的时间戳,则等待下一毫秒
        int i = 0;
        while (timestamp <= lastTimestamp) {
            System.out.println(++i);
            timestamp = timeGen();
        }
        i= 0;
        return timestamp;
    }

    /**
     * 获取当前时间戳(毫秒级)
     *
     * @return 当前时间戳
     */
    private static long timeGen() {
        return System.currentTimeMillis();
    }

    private static String getIp() throws UnknownHostException{
        InetAddress ip = InetAddress.getLocalHost();
        System.out.println("IP地址: " + ip.getHostAddress());
        return ip.getHostAddress();
    }

    public static void main(String[] args) {
        UniqueIdUtils gerator = new UniqueIdUtils();
        for (int i = 0; i < 10000; i++) {
            System.out.println(gerator.nextId());
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
雪花算法是一种分布式唯一ID生成算法,可以生成全局唯一且有序的ID。以下是使用雪花算法生成交易订单ID的示例代码: ```java public class SnowflakeIdGenerator { private final long epoch = 1609459200000L; // 2021-01-01 00:00:00 private final long workerIdBits = 5L; private final long datacenterIdBits = 5L; private final long sequenceBits = 12L; private final long maxWorkerId = -1L ^ (-1L << workerIdBits); private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); private final long workerIdShift = sequenceBits; private final long datacenterIdShift = sequenceBits + workerIdBits; private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; private final long sequenceMask = -1L ^ (-1L << sequenceBits); private long workerId; private long datacenterId; private long sequence = 0L; private long lastTimestamp = -1L; public SnowflakeIdGenerator(long workerId, long datacenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException("workerId can't be greater than " + maxWorkerId + " or less than 0"); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException("datacenterId can't be greater than " + maxDatacenterId + " or less than 0"); } this.workerId = workerId; this.datacenterId = datacenterId; } public synchronized long nextId() { long timestamp = System.currentTimeMillis() - epoch; if (timestamp < lastTimestamp) { throw new RuntimeException("Clock moved backwards. Refusing to generate id"); } if (timestamp == lastTimestamp) { sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; return (timestamp << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; } private long tilNextMillis(long lastTimestamp) { long timestamp = System.currentTimeMillis() - epoch; while (timestamp <= lastTimestamp) { timestamp = System.currentTimeMillis() - epoch; } return timestamp; } } ``` 使用示例: ```java SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1); long orderId = idGenerator.nextId(); System.out.println("orderId = " + orderId); ``` 输出结果: ``` orderId = 243374213386881 ``` 生成的订单ID是一个64位的long类型数字,其中前41位是时间戳,5位是数据中心ID,5位是工作节点ID,12位是序列号。可以保证在分布式系统中生成ID全局唯一的,并且可以根据时间戳排序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值