zoukankan      html  css  js  c++  java
  • 全局唯一性ID生成方法小结

    全局ID通常要满足分片的一些要求:
    1 不能有单点故障。
    2 以时间为序,或者ID里包含时间。这样一是可以少一个索引,二是冷热数据容易分离。
    3 可以控制ShardingId。比如某一个用户的文章要放在同一个分片内,这样查询效率高,修改也容易。
    4 不要太长,最好64bit。使用long比较好操作,如果是96bit,那就要各种移位相当的不方便,还有可能有些组件不能支持这么大的ID。

    一、UUID

    UUID生成的是length=32的16进制格式的字符串,如果回退为byte数组共16个byte元素,即UUID是一个128bit长的数字,
    一般用16进制表示。
    算法的核心思想是结合机器的网卡、当地时间、一个随即数来生成UUID。
    从理论上讲,如果一台机器每秒产生10000000个GUID,则可以保证(概率意义上)3240年不重复
    优点:
    (1)本地生成ID,不需要进行远程调用,时延低
    (2)扩展性好,基本可以认为没有性能上限
    缺点:
    (1)无法保证趋势递增
    (2)uuid过长,往往用字符串表示,作为主键建立索引查询效率低,常见优化方案为“转化为两个uint64整数存储”或者“折半存储”(折半后不能保证唯一性)

    二、基于redis的分布式ID生成器

    原理
    利用redis的lua脚本执行功能,在每个节点上通过lua脚本生成唯一ID。
    生成的ID是64位的:
    使用41 bit来存放时间,精确到毫秒,可以使用41年。
    使用12 bit来存放逻辑分片ID,最大分片ID是4095
    使用10 bit来存放自增长ID,意味着每个节点,每毫秒最多可以生成1024个ID
    比如GTM时间 Fri Mar 13 10:00:00 CST 2015 ,它的距1970年的毫秒数是 1426212000000,假定分片ID是53,自增长序列是4,则生成的ID是:
    5981966696448054276 = 1426212000000 << 22 + 53 << 10 + 41
    redis提供了TIME命令,可以取得redis服务器上的秒数和微秒数。因些lua脚本返回的是一个四元组。
    second, microSecond, partition, seq
    客户端要自己处理,生成最终ID。
    ((second * 1000 + microSecond / 1000) << (12 + 10)) + (shardId << 10) + seq;

    三、MongoDB文档(Document)全局唯一ID

    为了考虑分布式,“_id”要求不同的机器都能用全局唯一的同种方法方便的生成它。因此不能使用自增主键(需要多台服务器进行同步,既费时又费力),
    因此选用了生成ObjectId对象的方法。

    ObjectId使用12字节的存储空间,其生成方式如下:
    |0|1|2|3|4|5|6 |7|8|9|10|11|
    |时间戳 |机器ID|PID|计数器 |

    前四个字节时间戳是从标准纪元开始的时间戳,单位为秒,有如下特性:
    1)时间戳与后边5个字节一块,保证秒级别的唯一性;
    2)保证插入顺序大致按时间排序;
    3)隐含了文档创建时间;
    4)时间戳的实际值并不重要,不需要对服务器之间的时间进行同步(因为加上机器ID和进程ID已保证此值唯一,唯一性是ObjectId的最终诉求)。
    机器ID是服务器主机标识,通常是机器主机名的散列值。
    同一台机器上可以运行多个mongod实例,因此也需要加入进程标识符PID。
    前9个字节保证了同一秒钟不同机器不同进程产生的ObjectId的唯一性。后三个字节是一个自动增加的计数器(一个mongod进程需要一个全局的计数器),保证同一秒的ObjectId是唯一的。同一秒钟最多允许每个进程拥有(256^3 = 16777216)个不同的ObjectId。

    总结一下:时间戳保证秒级唯一,机器ID保证设计时考虑分布式,避免时钟同步,PID保证同一台服务器运行多个mongod实例时的唯一性,最后的计数器保证同一秒内的唯一性(选用几个字节既要考虑存储的经济性,也要考虑并发性能的上限)。
    "_id"既可以在服务器端生成也可以在客户端生成,在客户端生成可以降低服务器端的压力。

    四、自定义32位GUID

    原理:14位的当前系统时间(格式为:yyyyMMddHHmmss) + 当前电脑的IP地址的最后两位 + 当前线程的hashCode的前9位 + 7位的随机数

    /**
     * GUID构造器
     * 32位:14位当前系统时间(yyyyMMddHHmmss) + 当前电脑的IP地址的最后两位 + 当前线程的hashCode的前9位 + 7位的随机数
     * 19位:12位当前系统时间(yyMMddHHmmss) + 当前线程的hashCode的前3位 + 4位的随机数
     * @author Administrator
     * @create 2018-03-17 14:35
     */
    public class UniqId {
        private static UniqId me = new UniqId();
        private String hostAddr;
        private final Random random = new SecureRandom();
        private final UniqTimer timer = new UniqTimer();
    
        private boolean isOutputInfo = false;
    
        private UniqId() {
            try {
                final InetAddress addr = InetAddress.getLocalHost();
                hostAddr = addr.getHostAddress();
            }catch (final IOException e) {
                System.err.println("[UniqID] Get HostAddr Error"+e);
                hostAddr = String.valueOf(System.currentTimeMillis());
            }
            if (null == hostAddr || hostAddr.trim().length() == 0 || "127.0.0.1".equals(hostAddr)) {
                hostAddr = String.valueOf(System.currentTimeMillis());
            }
            hostAddr = hostAddr.substring(hostAddr.length()-2).replace(".", "0");
            if(isOutputInfo){
                System.out.println("[UniqID]hostAddr is:" + hostAddr + "----length:"+hostAddr.length());
            }
        }
    
    
        /**
         * 获取UniqID实例
         * @return UniqId
         */
        public static UniqId getInstance() {
            me.isOutputInfo = false;
            return me;
        }
    
        /**
         * 获取UniqID实例
         * @return UniqId
         */
        public static UniqId getInstanceWithLog() {
            me.isOutputInfo = true;
            return me;
        }
    
    
        /**
         * 获得不会重复的毫秒数
         *
         * @return 不会重复的时间
         */
        public String getUniqTime() {
            String time = timer.getCurrentTime();
            if(isOutputInfo){
                System.out.println("[UniqID.getUniqTime]" + time +"----length:"+ time.length());
            }
            return time;
        }
    
        public String getUniqTime2() {
            String time = timer.getCurrentTime2();
            if(isOutputInfo){
                System.out.println("[UniqID.getUniqTime]" + time +"----length:"+ time.length());
            }
            return time;
        }
    
        /**
         * 获得UniqId
         *
         * @return uniqTime-randomNum-hostAddr-threadId
         */
        public String get32UniqID() {
            final StringBuffer sb = new StringBuffer();
            final String t = getUniqTime();
            int randomNumber = random.nextInt(8999999) + 1000000;
            sb.append(t);
            sb.append(hostAddr);
            sb.append(getUniqThreadCode());
            sb.append(randomNumber);
            if (isOutputInfo) {
                System.out.println("[UniqID.randomNumber]" + randomNumber+"----length:"+String.valueOf(randomNumber).length());
                System.out.println("[UniqID.getUniqID]" + sb.toString()+"----length:"+String.valueOf(sb).length());
            }
            return sb.toString();
        }
    
        /**
         * 获取19位GUID 不考虑分布式
         * @return
         */
        public Long get19UniqID() {
            final StringBuffer sb = new StringBuffer();
            final String t = getUniqTime2();
            int randomNumber = random.nextInt(8999) + 1000;
            sb.append(t);
            sb.append(getUniqThreadCode2());
            sb.append(randomNumber);
            return Long.parseLong(sb.toString());
        }
    
        public String getUniqThreadCode(){
            String threadCode = StringUtils.left(String.valueOf(Thread.currentThread().hashCode()),9);
            if (isOutputInfo) {
                System.out.println("[UniqID.getUniqThreadCode]" +threadCode+"----length:"+threadCode.length());
            }
            return StringUtils.leftPad(threadCode, 9, "0");
        }
    
        public String getUniqThreadCode2(){
            String threadCode = StringUtils.left(String.valueOf(Thread.currentThread().hashCode()),9);
            if (isOutputInfo) {
                System.out.println("[UniqID.getUniqThreadCode]" +threadCode+"----length:"+threadCode.length());
            }
            return StringUtils.leftPad(threadCode, 9, "0").substring(6);
        }
    
        /**
         * 实现不重复的时间
         */
        private class UniqTimer {
            private final AtomicLong lastTime = new AtomicLong(System.currentTimeMillis());
            public String getCurrentTime() {
                if(!timestamp2Date(this.lastTime.incrementAndGet()).equals(timestamp2Date(System.currentTimeMillis()))){
                    lastTime.set(System.currentTimeMillis()+random.nextInt(10000));
                }
                return timestamp2Datetimes(this.lastTime.incrementAndGet());
            }
    
            public String getCurrentTime2() {
                if(!timestamp2Date(this.lastTime.incrementAndGet()).equals(timestamp2Date(System.currentTimeMillis()))){
                    lastTime.set(System.currentTimeMillis()+random.nextInt(10000));
                }
                return timestamp2Datetimes2(this.lastTime.incrementAndGet());
            }
        }
    
        /**
         * 规范化日期,规范成yyyy-MM-dd
         * @param timestamp
         * @return
         */
        public static String timestamp2Date(long timestamp){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            return dateFormat.format(new Date(timestamp * 1000));
        }
    
        private static String timestamp2Datetimes(long timestamp){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            return dateFormat.format(new Date(timestamp));
        }
    
        private static String timestamp2Datetimes2(long timestamp){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss");
            return dateFormat.format(new Date(timestamp));
        }
    
    }
  • 相关阅读:
    0625jQuery练习:权限基础1:查询员工对应角色、修改员工对应角色
    0624jQuery练习:三级联动—时间
    0622jQuery基础:常用属性
    0621jQuery基础:基础属性
    0621jQuery练习:三级联动
    0621jQuery练习:弹窗
    0621jQuery基础:事件
    数据库连接-登录
    javaScript中的DOM操作及数组的使用
    设置日期对象(年-月-日 时-分-秒)实现菱形的拼接
  • 原文地址:https://www.cnblogs.com/archermeng/p/8590623.html
Copyright © 2011-2022 走看看