前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java 工具类,生成唯一的id值

java 工具类,生成唯一的id值

作者头像
一写代码就开心
发布2022-08-14 11:01:57
1.7K0
发布2022-08-14 11:01:57
举报
文章被收录于专栏:java和python

目录

1 代码

代码语言:javascript
复制
public class IdGenerator {

    public static final long WORKER_ID = ipKeyGenerator();
    private static long sequence;
    private static long lastTimestamp = -1L;

    public static synchronized String generateId() {
        long currentMillis = currentMillis();
        if (lastTimestamp == currentMillis) {
            sequence = sequence + 1L & 4095L;
            if (sequence == 0L) {
                currentMillis = waitUntilNextTime(currentMillis);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = currentMillis;
        long nextId = currentMillis - 1295884800000L << 22 | WORKER_ID << 12 | sequence;
        return String.valueOf(nextId);
    }

    private static long waitUntilNextTime(long lastTime) {
        long timestamp;
        for (timestamp = currentMillis(); timestamp <= lastTime; timestamp = currentMillis()) {
        }
        return timestamp;
    }

    private static long ipKeyGenerator() {
        InetAddress address;
        try {
            address = InetAddress.getLocalHost();
        } catch (final UnknownHostException e) {
            throw new IllegalStateException("cannot get localhost address, please check your network!");
        }
        byte[] ipAddressByteArray = address.getAddress();
        return ((long) (((ipAddressByteArray[ipAddressByteArray.length - 2] & 0B11) << Byte.SIZE) + (ipAddressByteArray[ipAddressByteArray.length - 1] & 0xFF)));
    }

    private static long currentMillis() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {
        System.out.println(generateId());
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-08-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 目录
  • 1 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档