分布式自增ID解决方案-Twitter Snowflake

    在大型互联网应用中,随着用户数的增加,为了提高应用的性能,我们经常需要对数据库进行分库分表操作。在单表时代,我们可以完全依赖于数据库的自增ID来唯一标识一

个用户或数据对象。

   但是当我们对数据库进行了分库分表后,就不能依赖于每个表的自增ID来全局唯一标识这些数据了。因为自增的id不能在分库分表的场景下,准确的路由到正确的数据。

   因此,我们需要提供一个全局唯一的ID号生成策略来支持分库分表的环境

    Twitter-Snowflake算法产生的背景相当简单,为了满足Twitter每秒上万条消息的请求,每条消息都必须分配一条唯一的id,这些id还需要一些大致的顺序(方

便客户端排序),并且在分布式系统中不同机器产生的id必须不同。


    除了最高位bit标记为不可用以外,其余三组bit占位均可浮动,看具体的业务需求而定。默认情况下41bit的时间戳可以支持该算法使用到2082年,10bit的工作机器id可以支持

1023台机器,序列号支持1毫秒产生4095个自增序列id。

    根据twitter的业务需求,snowflake系统生成64位的ID。由3部分组成:

  • 41位的时间序列(精确到毫秒,41位的长度可以使用69年)

  • 10位的机器标识(10位的长度最多支持部署1024个节点)

  • 12位的计数顺序号(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号)

    public class IdWorkerStandard {
        private final long workerIdBits = 10L;
        private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
        private final long sequenceBits = 12L;
        private final long workerIdShift = sequenceBits;
        private final long timestampLeftShift = sequenceBits + workerIdBits;
        private final long sequenceMask = -1L ^ (-1L << sequenceBits);
    
        private long workerId;
        private long sequence = 0L;
        private long lastTimestamp = -1L;
    
        public IdWorkerStandard(long workerId) {
            if (workerId > maxWorkerId || workerId < 0) {
                throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
            }
            this.workerId = workerId;
        }
    
        public synchronized long nextId() {
            long timestamp = timeGen();
            if (timestamp < lastTimestamp) {
                throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
            }
            if (lastTimestamp == timestamp) {
                sequence = (sequence + 1) & sequenceMask;
                if (sequence == 0) {
                    timestamp = tilNextMillis(lastTimestamp);
                }
            } else {
                sequence = 0L;
                //sequence = Math.round(Math.random() * 4096);
            }
    
            lastTimestamp = timestamp;
    
            return (timestamp << timestampLeftShift) | (workerId << workerIdShift) | sequence;
        }
    
        protected long tilNextMillis(long lastTimestamp) {
            long timestamp = timeGen();
            while (timestamp <= lastTimestamp) {
                timestamp = timeGen();
            }
            return timestamp;
        }
    
        protected long timeGen() {
            return System.currentTimeMillis();
        }
    
        public static void main(String[] args) {
            IdWorkerStandard idWorker = new IdWorkerStandard(0);
            for (int i = 0; i < 10; i++) {
                long id = idWorker.nextId();
                System.out.println(id);
            }
        }
    }
    


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值