分布式ID生成器

简介:

最近会写一篇分布式的ID生成器的文章,先占位。借鉴Mongodb的ObjectId的生成:

4byte时间戳 + 3byte机器标识 + 2byte PID + 3byte自增id

简单代码:

import com.google.common.base.Objects;
 
import java.net.NetworkInterface;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
 * <p>A globally unique identifier for objects.</p>
 * <p/>
 * <p>Consists of 12 bytes, divided as follows:</p>
 * <table border="1">
 * <caption>ObjectID layout</caption>
 * <tr>
 * <td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td><td>11</td>
 * </tr>
 * <tr>
 * <td colspan="4">time</td><td colspan="3">machine</td> <td colspan="2">pid</td><td colspan="3">inc</td>
 * </tr>
 * </table>
 * <p/>
 * <p>Instances of this class are immutable.</p>
 */
public class ObjectId implements Comparable<ObjectId>, java.io.Serializable {
 
    private final int _time;
    private final int _machine;
    private final int _inc;
    private boolean _new;
    private static final int _genmachine;
 
    private static AtomicInteger _nextInc = new AtomicInteger((new java.util.Random()).nextInt());
 
    private static final long serialVersionUID = -4415279469780082174L;
 
    private static final Logger LOGGER = Logger.getLogger("org.bson.ObjectId");
 
    /**
     * Create a new object id.
     */
    public ObjectId() {
        _time = (int) (System.currentTimeMillis() / 1000);
        _machine = _genmachine;
        _inc = _nextInc.getAndIncrement();
        _new = true;
    }
 
    /**
     * Gets a new object id.
     *
     * @return the new id
     */
    public static ObjectId get() {
        return new ObjectId();
    }
 
    /**
     * Checks if a string could be an {@code ObjectId}.
     *
     * @param s a potential ObjectId as a String.
     * @return whether the string could be an object id
     * @throws IllegalArgumentException if hexString is null
     */
    public static boolean isValid(String s) {
        if (s == null)
            return false;
 
        final int len = s.length();
        if (len != 24)
            return false;
 
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9')
                continue;
            if (c >= 'a' && c <= 'f')
                continue;
            if (c >= 'A' && c <= 'F')
                continue;
 
            return false;
        }
 
        return true;
    }
 
 
    /**
     * Converts this instance into a 24-byte hexadecimal string representation.
     *
     * @return a string representation of the ObjectId in hexadecimal format
     */
    public String toHexString() {
        final StringBuilder buf = new StringBuilder(24);
        for (final byte b : toByteArray()) {
            buf.append(String.format("%02x", b & 0xff));
        }
        return buf.toString();
    }
 
    /**
     * Convert to a byte array.  Note that the numbers are stored in big-endian order.
     *
     * @return the byte array
     */
    public byte[] toByteArray() {
        byte b[] = new byte[12];
        ByteBuffer bb = ByteBuffer.wrap(b);
        // by default BB is big endian like we need
        bb.putInt(_time);
        bb.putInt(_machine);
        bb.putInt(_inc);
        return b;
    }
 
    private int _compareUnsigned(int i, int j) {
        long li = 0xFFFFFFFFL;
        li = i & li;
        long lj = 0xFFFFFFFFL;
        lj = j & lj;
        long diff = li - lj;
        if (diff < Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        if (diff > Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
        return (int) diff;
    }
 
    public int compareTo(ObjectId id) {
        if (id == null)
            return -1;
 
        int x = _compareUnsigned(_time, id._time);
        if (x != 0)
            return x;
 
        x = _compareUnsigned(_machine, id._machine);
        if (x != 0)
            return x;
 
        return _compareUnsigned(_inc, id._inc);
    }
 
    /**
     * Gets the timestamp (number of seconds since the Unix epoch).
     *
     * @return the timestamp
     */
    public int getTimestamp() {
        return _time;
    }
 
    /**
     * Gets the timestamp as a {@code Date} instance.
     *
     * @return the Date
     */
    public Date getDate() {
        return new Date(_time * 1000L);
    }
 
 
    /**
     * Gets the current value of the auto-incrementing counter.
     *
     * @return the current counter value.
     */
    public static int getCurrentCounter() {
        return _nextInc.get();
    }
 
 
    static {
 
        try {
            // build a 2-byte machine piece based on NICs info
            int machinePiece;
            {
                try {
                    StringBuilder sb = new StringBuilder();
                    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
                    while (e.hasMoreElements()) {
                        NetworkInterface ni = e.nextElement();
                        sb.append(ni.toString());
                    }
                    machinePiece = sb.toString().hashCode() << 16;
                } catch (Throwable e) {
                    // exception sometimes happens with IBM JVM, use random
                    LOGGER.log(Level.WARNING, e.getMessage(), e);
                    machinePiece = (new Random().nextInt()) << 16;
                }
                LOGGER.fine("machine piece post: " + Integer.toHexString(machinePiece));
            }
 
            // add a 2 byte process piece. It must represent not only the JVM but the class loader.
            // Since static var belong to class loader there could be collisions otherwise
            final int processPiece;
            {
                int processId = new java.util.Random().nextInt();
                try {
                    processId = java.lang.management.ManagementFactory.getRuntimeMXBean().getName().hashCode();
                } catch (Throwable t) {
                }
 
                ClassLoader loader = ObjectId.class.getClassLoader();
                int loaderId = loader != null ? System.identityHashCode(loader) : 0;
 
                StringBuilder sb = new StringBuilder();
                sb.append(Integer.toHexString(processId));
                sb.append(Integer.toHexString(loaderId));
                processPiece = sb.toString().hashCode() & 0xFFFF;
                LOGGER.fine("process piece: " + Integer.toHexString(processPiece));
            }
 
            _genmachine = machinePiece | processPiece;
            LOGGER.fine("machine : " + Integer.toHexString(_genmachine));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
 
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
 
        ObjectId that = (ObjectId) o;
 
        return Objects.equal(this.serialVersionUID, that.serialVersionUID) &&
                Objects.equal(this.LOGGER, that.LOGGER) &&
                Objects.equal(this._time, that._time) &&
                Objects.equal(this._machine, that._machine) &&
                Objects.equal(this._inc, that._inc) &&
                Objects.equal(this._new, that._new) &&
                Objects.equal(this._nextInc, that._nextInc) &&
                Objects.equal(this._genmachine, that._genmachine);
    }
 
    @Override
    public int hashCode() {
        return Objects.hashCode(serialVersionUID, LOGGER, _time, _machine, _inc, _new,
                _nextInc, _genmachine);
    }
 
    public static void main(String[] args) {
        System.out.println(new ObjectId().toHexString());
        System.out.println(new ObjectId().toHexString());
        System.out.println(new ObjectId().toHexString());
    }
}

参考资料:

目录
相关文章
|
前端开发 JavaScript UED
探索Python Django中的WebSocket集成:为前后端分离应用添加实时通信功能
通过在Django项目中集成Channels和WebSocket,我们能够为前后端分离的应用添加实时通信功能,实现诸如在线聊天、实时数据更新等交互式场景。这不仅增强了应用的功能性,也提升了用户体验。随着实时Web应用的日益普及,掌握Django Channels和WebSocket的集成将为开发者开启新的可能性,推动Web应用的发展迈向更高层次的实时性和交互性。
275 1
|
存储 关系型数据库 MySQL
什么是联合索引
【10月更文挑战第15天】什么是联合索引
836 4
|
开发工具 git
【Azure App Service】App Service设置访问限制后,使用git clone代码库出现403报错
【Azure App Service】App Service设置访问限制后,使用git clone代码库出现403报错
211 3
|
搜索推荐 安全 数据安全/隐私保护
构建高效网站后台会员管理系统:实战指南与代码示例
【7月更文挑战第5天】在当今的互联网时代,几乎每个网站或应用程序都需要一个强大的会员管理系统来维护用户信息、权限控制以及个性化体验。一个设计良好的会员管理系统不仅能够提升用户体验,还能增强数据安全性和运营效率。本文将深入探讨如何从零开始构建一个网站后台会员管理系统,涵盖系统设计思路、关键技术选型、功能模块实现,以及实战代码示例。
1259 3
|
11月前
|
前端开发 测试技术 数据库
DDD架构中assembler和converter的区别
在 DDD 四层架构模式中,assembler 和 converter 常用于对象转换,但两者在实际项目中的使用较为随意。本文从英文释义、语义区分和模型层区分三个方面探讨了两者的区别,建议按模型层区分,即 Interface 和 Application 层使用 assembler,Infrastructure 层使用 converter,以避免混淆和随意使用。此外,将转换代码抽离为独立方法有助于保持代码整洁和可测试性。
|
存储 算法 NoSQL
常见分布式ID解决方案总结:数据库、算法、开源组件
分布式ID解决方案是用于在分布式系统中生成唯一标识符的方案。常见的分布式ID解决方案可总结为3点:数据库方案、算法方案、开源组件方案。
990 1
常见分布式ID解决方案总结:数据库、算法、开源组件
|
安全 Java C++
CAS自旋锁到底是什么?为什么能实现线程安全?
本文是博主对多线程学习总结记录,希望对大家有所帮助。
1479 0
CAS自旋锁到底是什么?为什么能实现线程安全?
|
弹性计算 安全 Linux
阿里云Alibaba Cloud Linux镜像系统怎么样?有用过的吗?
Alibaba Cloud Linux是阿里云推出的Linux发行版,Alibaba Cloud Linux是基于龙蜥社区OpenAnolis龙蜥操作系统Anolis OS。Alibaba Cloud Linux针对云服务器ECS进行了深度优化,CentOS停止维护完全可以使用Alibaba Cloud Linux代替,Alibaba Cloud Linux兼容CentOS/RHEL生态,CentOS/RHEL中的大多数软件无需或仅需少量改造即可在Alibaba Cloud Linux中运行。
1372 0
阿里云Alibaba Cloud Linux镜像系统怎么样?有用过的吗?
|
负载均衡 前端开发 API
构建高效的BFF(Backend for Frontend):优化前端与后端协作
构建高效的BFF(Backend for Frontend):优化前端与后端协作
1251 0
|
Java
7.1 深入理解闭包与内部类:闭包的概念与应用
7.1 深入理解闭包与内部类:闭包的概念与应用
400 0