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

来源:互联网 发布:centos 7内核支持ntfS 编辑:程序博客网 时间:2024/05/16 14:46

    在大型互联网应用中,随着用户数的增加,为了提高应用的性能,我们经常需要对数据库进行分库分表操作。在单表时代,我们可以完全依赖于数据库的自增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 0