李锋镝的博客

  • 首页
  • 时间轴
  • 说说
  • 读书观影
  • 系列
  • AI工具集
  • 论坛
  • 友圈
    • 友链
    • 朋友圈
    • 游客中心
  • 留言
    • 留言
    • 走心评论
  • 关于
    • 关于本站
    • Now
    • 每日心情
    • 网站地图
    • 网站统计
    • 赞助
  • 星球穿梭
  • 🚇开往
静亦定 动亦定
惟坚韧者始能遂其志
  1. 首页
  2. 中间件
  3. 正文

分布式服务生成唯一不重复ID(24位字符串)

2019年7月13日 261 0 0
本文最后更新于 2025年11月20日,距今已 355 天,其中的信息可能已经发生变化,请注意甄别。

参照mongoDB的ID生成策略,生成唯一ID。

一共12个字节(示例:5cecf0a8a7573ea439fa1a89)

前4个字节表示时间戳
再往后数3个字节表示运行当前程序的机器ID
再往后2个字节表示生成此id的进程的ID
最后3个字节表示由一个随机数开始的计数器生成的值

然后转为16进制的字符串。

源码如下:

import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.net.NetworkInterface;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 李锋镝
 * @date Create at 20:26 2018/12/21
 */
@Slf4j
public final class GeneratorId implements Comparable<GeneratorId>, Serializable {

    private static final long serialVersionUID = 440848443996694196L;

    private static final int LOW_ORDER_THREE_BYTES = 0x00ffffff;

    private static final int MACHINE_IDENTIFIER;
    private static final short PROCESS_IDENTIFIER;
    private static final AtomicInteger NEXT_COUNTER = new AtomicInteger(new SecureRandom().nextInt());

    private static final char[] HEX_CHARS = new char[] {
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    private final int timestamp;
    private final int machineIdentifier;
    private final short processIdentifier;
    private final int counter;

    public static GeneratorId get() {
        return new GeneratorId();
    }


    public static boolean isValid(final String hexString) {
        if (hexString == null) {
            throw new IllegalArgumentException();
        }

        int len = hexString.length();
        if (len != 24) {
            return false;
        }

        for (int i = 0; i < len; i++) {
            char c = hexString.charAt(i);
            if (c >= '0' && c <= '9') {
                continue;
            }
            if (c >= 'a' && c <= 'f') {
                continue;
            }
            if (c >= 'A' && c <= 'F') {
                continue;
            }

            return false;
        }

        return true;
    }


    public static int getGeneratedMachineIdentifier() {
        return MACHINE_IDENTIFIER;
    }


    public static int getGeneratedProcessIdentifier() {
        return PROCESS_IDENTIFIER;
    }


    public static int getCurrentCounter() {
        return NEXT_COUNTER.get();
    }


    public static GeneratorId createFromLegacyFormat(final int time, final int machine, final int inc) {
        return new GeneratorId(time, machine, inc);
    }

    public GeneratorId() {
        this(new Date());
    }


    public GeneratorId(final Date date) {
        this(dateToTimestampSeconds(date), MACHINE_IDENTIFIER, PROCESS_IDENTIFIER, NEXT_COUNTER.getAndIncrement(), false);
    }


    public GeneratorId(final Date date, final int counter) {
        this(date, MACHINE_IDENTIFIER, PROCESS_IDENTIFIER, counter);
    }


    public GeneratorId(final Date date, final int machineIdentifier, final short processIdentifier, final int counter) {
        this(dateToTimestampSeconds(date), machineIdentifier, processIdentifier, counter);
    }


    public GeneratorId(final int timestamp, final int machineIdentifier, final short processIdentifier, final int counter) {
        this(timestamp, machineIdentifier, processIdentifier, counter, true);
    }

    private GeneratorId(final int timestamp, final int machineIdentifier, final short processIdentifier, final int counter,
                     final boolean checkCounter) {
        if ((machineIdentifier & 0xff000000) != 0) {
            throw new IllegalArgumentException("The machine identifier must be between 0 and 16777215 (it must fit in three bytes).");
        }
        if (checkCounter && ((counter & 0xff000000) != 0)) {
            throw new IllegalArgumentException("The counter must be between 0 and 16777215 (it must fit in three bytes).");
        }
        this.timestamp = timestamp;
        this.machineIdentifier = machineIdentifier;
        this.processIdentifier = processIdentifier;
        this.counter = counter & LOW_ORDER_THREE_BYTES;
    }


    public GeneratorId(final String hexString) {
        this(parseHexString(hexString));
    }


    public GeneratorId(final byte[] bytes) {
        this(ByteBuffer.wrap(notNull("bytes", bytes)));
    }


    GeneratorId(final int timestamp, final int machineAndProcessIdentifier, final int counter) {
        this(legacyToBytes(timestamp, machineAndProcessIdentifier, counter));
    }


    public GeneratorId(final ByteBuffer buffer) {
        notNull("buffer", buffer);
        isTrueArgument("buffer.remaining() >=12", buffer.remaining() >= 12);

        timestamp = makeInt(buffer.get(), buffer.get(), buffer.get(), buffer.get());
        machineIdentifier = makeInt((byte) 0, buffer.get(), buffer.get(), buffer.get());
        processIdentifier = (short) makeInt((byte) 0, (byte) 0, buffer.get(), buffer.get());
        counter = makeInt((byte) 0, buffer.get(), buffer.get(), buffer.get());
    }

    private static byte[] legacyToBytes(final int timestamp, final int machineAndProcessIdentifier, final int counter) {
        byte[] bytes = new byte[12];
        bytes[0] = int3(timestamp);
        bytes[1] = int2(timestamp);
        bytes[2] = int1(timestamp);
        bytes[3] = int0(timestamp);
        bytes[4] = int3(machineAndProcessIdentifier);
        bytes[5] = int2(machineAndProcessIdentifier);
        bytes[6] = int1(machineAndProcessIdentifier);
        bytes[7] = int0(machineAndProcessIdentifier);
        bytes[8] = int3(counter);
        bytes[9] = int2(counter);
        bytes[10] = int1(counter);
        bytes[11] = int0(counter);
        return bytes;
    }

    public byte[] toByteArray() {
        ByteBuffer buffer = ByteBuffer.allocate(12);
        putToByteBuffer(buffer);
        return buffer.array();  // using .allocate ensures there is a backing array that can be returned
    }

    public void putToByteBuffer(final ByteBuffer buffer) {
        notNull("buffer", buffer);
        isTrueArgument("buffer.remaining() >=12", buffer.remaining() >= 12);

        buffer.put(int3(timestamp));
        buffer.put(int2(timestamp));
        buffer.put(int1(timestamp));
        buffer.put(int0(timestamp));
        buffer.put(int2(machineIdentifier));
        buffer.put(int1(machineIdentifier));
        buffer.put(int0(machineIdentifier));
        buffer.put(short1(processIdentifier));
        buffer.put(short0(processIdentifier));
        buffer.put(int2(counter));
        buffer.put(int1(counter));
        buffer.put(int0(counter));
    }

    public int getTimestamp() {
        return timestamp;
    }

    public int getMachineIdentifier() {
        return machineIdentifier;
    }

    public short getProcessIdentifier() {
        return processIdentifier;
    }

    public int getCounter() {
        return counter;
    }

    public Date getDate() {
        return new Date(timestamp * 1000L);
    }

    public String toHexString() {
        char[] chars = new char[24];
        int i = 0;
        for (byte b : toByteArray()) {
            chars[i++] = HEX_CHARS[b >> 4 & 0xF];
            chars[i++] = HEX_CHARS[b & 0xF];
        }
        return new String(chars);
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        GeneratorId GeneratorId = (GeneratorId) o;

        if (counter != GeneratorId.counter) {
            return false;
        }
        if (machineIdentifier != GeneratorId.machineIdentifier) {
            return false;
        }
        if (processIdentifier != GeneratorId.processIdentifier) {
            return false;
        }
        if (timestamp != GeneratorId.timestamp) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = timestamp;
        result = 31 * result + machineIdentifier;
        result = 31 * result + (int) processIdentifier;
        result = 31 * result + counter;
        return result;
    }

    @Override
    public int compareTo(final GeneratorId other) {
        if (other == null) {
            throw new NullPointerException();
        }

        byte[] byteArray = toByteArray();
        byte[] otherByteArray = other.toByteArray();
        for (int i = 0; i < 12; i++) {
            if (byteArray[i] != otherByteArray[i]) {
                return ((byteArray[i] & 0xff) < (otherByteArray[i] & 0xff)) ? -1 : 1;
            }
        }
        return 0;
    }

    @Override
    public String toString() {
        return toHexString();
    }

    static {
        try {
            MACHINE_IDENTIFIER = createMachineIdentifier();
            PROCESS_IDENTIFIER = createProcessIdentifier();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static int createMachineIdentifier() {
        int machinePiece;
        try {
            StringBuilder sb = new StringBuilder();
            Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
            while (e.hasMoreElements()) {
                NetworkInterface ni = e.nextElement();
                sb.append(ni.toString());
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    ByteBuffer bb = ByteBuffer.wrap(mac);
                    try {
                        sb.append(bb.getChar());
                        sb.append(bb.getChar());
                        sb.append(bb.getChar());
                    } catch (BufferUnderflowException shortHardwareAddressException) { //NOPMD
                        // mac with less than 6 bytes. continue
                    }
                }
            }
            machinePiece = sb.toString().hashCode();
        } catch (Throwable t) {
            machinePiece = (new SecureRandom().nextInt());
            log.error("Failed to get machine identifier from network interface, using random number instead", t);
        }
        machinePiece = machinePiece & LOW_ORDER_THREE_BYTES;
        return machinePiece;
    }

    private static short createProcessIdentifier() {
        short processId;
        try {
            String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
            if (processName.contains("@")) {
                processId = (short) Integer.parseInt(processName.substring(0, processName.indexOf('@')));
            } else {
                processId = (short) java.lang.management.ManagementFactory.getRuntimeMXBean().getName().hashCode();
            }

        } catch (Throwable t) {
            processId = (short) new SecureRandom().nextInt();
            log.error("Failed to get process identifier from JMX, using random number instead", t);
        }

        return processId;
    }

    private static byte[] parseHexString(final String s) {
        if (!isValid(s)) {
            throw new IllegalArgumentException("invalid hexadecimal representation of an GeneratorId: [" + s + "]");
        }

        byte[] b = new byte[12];
        for (int i = 0; i < b.length; i++) {
            b[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
        }
        return b;
    }

    private static int dateToTimestampSeconds(final Date time) {
        return (int) (time.getTime() / 1000);
    }

    private static int makeInt(final byte b3, final byte b2, final byte b1, final byte b0) {
        return (((b3) << 24) |
                ((b2 & 0xff) << 16) |
                ((b1 & 0xff) << 8) |
                ((b0 & 0xff)));
    }

    private static byte int3(final int x) {
        return (byte) (x >> 24);
    }

    private static byte int2(final int x) {
        return (byte) (x >> 16);
    }

    private static byte int1(final int x) {
        return (byte) (x >> 8);
    }

    private static byte int0(final int x) {
        return (byte) (x);
    }

    private static byte short1(final short x) {
        return (byte) (x >> 8);
    }

    private static byte short0(final short x) {
        return (byte) (x);
    }

    private static <T> T notNull(final String name, final T value) {
        if (value == null) {
            throw new IllegalArgumentException(name + " can not be null");
        }
        return value;
    }

    private static void isTrueArgument(final String name, final boolean condition) {
        if (!condition) {
            throw new IllegalArgumentException("state should be: " + name);
        }
    }
}

 

调用示例:

import com.lifengdi.util.GeneratorId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.StringJoiner;


/**
 * 生成唯一key
 * @author 李锋镝
 * @date Create at 13:45 2018/12/6
 */
@Component
@Slf4j
public class GeneratedKey {

    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 生成24位的16进制的key
     * @return key
     */
    public String generatorKey() {

        return GeneratorId.get().toString();
    }


    public static void main(String[] args) {
        GeneratedKey generatedKey = new GeneratedKey();
        System.out.println(generatedKey.generatorKey());
    }

    /**
     * 获取当前机器ID
     * @return MachineIdentifier
     */
    public int getMachineIdentifier() {
        return GeneratorId.getGeneratedMachineIdentifier();
    }

    /**
     * 获取当前进程ID
     * @return ProcessIdentifier
     */
    public int getProcessIdentifier() {
        return GeneratorId.getGeneratedProcessIdentifier();
    }

    /**
     * 获取当前项目唯一ID
     * @return ProjectIdentifier
     */
    public String getProjectIdentifier() {
        StringJoiner joiner = new StringJoiner("_");
        joiner.add(applicationName);
        joiner.add(String.valueOf(getMachineIdentifier()));
        joiner.add(String.valueOf(getProcessIdentifier()));
        return joiner.toString();
    }

}

 

其他分布式ID生成算法:分布式ID生成算法SnowFlake(雪花算法)Java源码

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
分享到

分布式服务生成唯一不重复ID(24位字符串)

也可使用浏览器菜单中的「分享」功能

微信扫一扫分享

标签: JAVA MySQL Spring SpringBoot 分布式 数据库
最后更新:2025年11月20日

岁月同一天 11 月 11 日

回望过去的今天,你在写什么

  • AI
    1 年前 2025年11月11日
    深度解析 RAG 技术:从原理到落地,构建高精度检索增强生成系统

    在企业知识库问答、专业文档处理、智能客服等场景中,大语言模型(LLM)常常面临“答非所问”“信息过时”“泄露隐私”等问题…

  • AI
    1 年前 2025年11月11日
    深度实战:基于 LangGraph + MCP 的智能音乐推荐 Agent 全解析(从搭建到落地)

    在 AI 与推荐系统结合的浪潮中,传统音乐推荐往往局限于“基于协同过滤”或“关键词匹配”,无法理解用户自然语言中的模糊需…

  • AI
    1 年前 2025年11月11日
    MCP深度解析:从协议本质到实战落地,彻底搞懂 AI 工具交互的标准化方案

    在 AI 工具化的浪潮中,Function Call 让 LLM 具备了调用外部工具的能力,但随着工具数量增多、LLM …

  • 5 年前 2021年11月11日
    WordPress的自动更新好烦啊

    昨晚突然收到邮件,说是WordPress自动更新到最新版了,好烦啊…… 每次更新完之后就得改一大堆东西,太坑了,今天终于…

  • 7 年前 2019年11月11日
    分布式锁-Zookeeper实现分布式锁

    如何用Zookeeper实现分布式锁? 在学习分布式锁之前,需要首先了解一下Zookeeper的[临时顺序节点]。 什么…

  • 7 年前 2019年11月11日
    再小的应用也有架构,面向架构新手的架构实践!

    文章主人公:小明,就职于某互联网公司,从事后端开发工作。最近小明收到通知公司需要开发一款《证件照》应用,需要征集架构方案…

  • 7 年前 2019年11月11日
    分布式锁-Java常用技术方案

    前言:       由于在平时的工作中,线上服务器是分布式多台部署的,经常会面临解决分布式场景下数据一致性的问题,那么就…

  • 7 年前 2019年11月11日
    在微服务中使用领域事件

    稍微回想一下计算机硬件的工作原理我们便不难发现,整个计算机的工作过程其实就是一个对事件的处理过程。当你点击鼠标、敲击键盘…

相关文章
  • 分库分表正在被淘汰?NewSQL与分库分表的深度博弈与选型指南2025年11月3日
  • Java设计模式:模板方法模式2025年5月21日
  • MySQL深度分页2022年2月11日
  • @Resource 和 @Autowired 的区别2022年6月24日
  • ThreadLocal如何解决内存泄漏问题2024年4月12日

李锋镝

既然选择了远方,便只顾风雨兼程。

打赏 点赞
< 上一篇
下一篇 >
1234567891112131415161718192021222324252627282930313233343536373839404142434446474849505152535455575859606162636465666769727476777879808182858687909293949596979899
取消回复
…

文章评论

还没有评论,快来抢沙发吧~

山有木兮木有枝,心悦君兮君不知。

听点儿音乐吧 朋友~
文章目录
最新 热点 随机
最新 热点 随机
给服务器加了WAF 又一个逆天改命的人:小小徐 AI的生成能力等于生产力吗? NGINX严重漏洞(CVE-2026-15176、CVE-2026-93479、CVE-2026-97205) Kratos-plus v1.1.27更新说明 php2shell远程执行漏洞修复(CVE-2026-109618 和 CVE-2026-109619)
给主题增加了游客中心功能心气没了,干什么都不得劲给服务器加了WAF我觉得是时候公布我的导航网站了游本昌去世关于主题加载速度优化的一点儿小演进
Java设计模式:策略模式 Chrome等浏览器下出现net::ERR_BLOCKED_BY_CLIENT的解决办法 Java布尔运算 CPU飙高,系统性能问题如何排查? 以面试官视角万字解读线程池10大经典面试题 关于Elasticsearch文档的描述以及如何操作文档的详细总结
最近评论
李锋镝 发布于 1 天前(11月09日) 我也刷到了,说是恶意引流的
皮皮社长 发布于 1 天前(11月09日) 我刷到的,怎么是说剧本骗流量的?如果真的是用来骗流量,那真恶心。欺骗网友感情。
李锋镝 发布于 2 天前(11月09日) 现在我这个是十个,其实也够用了
老张博客 发布于 2 天前(11月09日) 雷池唯一不好的就是只能免费5个网站。
fairy 发布于 4 天前(11月06日) 机器人快来我这里吧!
标签聚合
AI编程 JAVA AI IDEA 分布式 Claude SpringBoot K8s 日常 Theme ElasticSearch WordPress Redis 多线程 架构 数据库 MySQL JVM Spring SQL
友情链接
  • 刘永博客
  • Mr.Sun的博客
  • 韩情脉脉
  • Honesty
  • 林羽凡
  • 志文工作室
  • 彬红茶日记
  • 九仞之行
  • 老张博客
  • Serendipity
  • 瓦匠个人小站
  • 懋和道人
  • sssr7844的博客
  • 知向前端
  • lijie blog
  • 搬砖日记
  • 哥斯拉
  • 韩小韩博客
  • 皮皮社

COPYRIGHT © 2016-2026 lifengdi.com. ALL RIGHTS RESERVED.

lifengdi.com 十年之约虫洞

Domain age badge for lifengdi.com

Theme Kratos-plus By Dylan Li

津ICP备2024022503号-3

京公网安备11011502039375号