`
javafan_303
  • 浏览: 950383 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Twitter-Snowflake 自增id实现

 
阅读更多

 

package io.github.id;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间,然后5位datacenter标识位,</br>
 * 5位机器ID(并不算标识符,实际是为线程标识),然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。
 * 0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000
 * @author cailin
 *
 */
public class IdWorker {
     
    protected static final Logger LOG = LoggerFactory.getLogger(IdWorker.class);
     
    //机器id
    private long workerId;
    
    //数据中心id
    private long datacenterId;
    private long sequence = 0L;
 
    private long twepoch = 1288834974657L;
 
    //机器标识位数
    private long workerIdBits = 5L;
    //数据中心标识位数
    private long datacenterIdBits = 5L;
    //机器ID最大值
    private long maxWorkerId = -1L ^ (-1L << workerIdBits);
    //数据中心ID最大值
    private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    //毫秒内自增位
    private long sequenceBits = 12L;
    //机器ID偏左移12位
    private long workerIdShift = sequenceBits;
    //数据中心ID左移17位
    private long datacenterIdShift = sequenceBits + workerIdBits;
    //时间毫秒左移22位
    private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private long sequenceMask = -1L ^ (-1L << sequenceBits);
 
    private long lastTimestamp = -1L;
 
    /**
     * @param workerId 机器id
     * @param datacenterId 数据中心id
     */
    public IdWorker(long workerId, long datacenterId) {
        // sanity check for workerId
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        LOG.info(String.format("worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d", timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId));
    }
 
    public synchronized long nextId() {
        long timestamp = timeGen();
 
        if (timestamp < lastTimestamp) {
            LOG.error(String.format("clock is moving backwards.  Rejecting requests until %d.", lastTimestamp));
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
 
        if (lastTimestamp == timestamp) {
        	//当前毫秒内,则+1
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
            //当前毫秒内计数满了,则等待下一秒
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
 
        lastTimestamp = timestamp;
        
        //ID偏移组合生成最终的ID,并返回ID   
 
        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (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) {
    	IdWorker  worker  = new IdWorker(1, 1);
    	worker.nextId();
    	
	}
}

 

 

    PHP实现

 

<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 5                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available through the world-wide-web at the following url:           |
// | http://www.php.net/license/3_0.txt.                                  |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Original Author <author@example.com>                        |
// |          Your Name <you@example.com>                                 |
// +----------------------------------------------------------------------+
//
// $Id:$

class Idwork {
    const debug = 1;
    static $workerId;
    static $twepoch = 1361775855078;
    static $sequence = 0;
    const workerIdBits = 4;
    static $maxWorkerId = 15;
    const sequenceBits = 10;
    static $workerIdShift = 10;
    static $timestampLeftShift = 14;
    static $sequenceMask = 1023;
    private static $lastTimestamp = - 1;
    function __construct($workId) {
        if ($workId > self::$maxWorkerId || $workId < 0) {
            throw new Exception("worker Id can't be greater than 15 or less than 0");
        }
        self::$workerId = $workId;
        echo 'logdebug->__construct()->self::$workerId:' . self::$workerId;
        echo '</br>';
    }
    function timeGen() {
        //获得当前时间戳
        $time = explode(' ', microtime());
        $time2 = substr($time[0], 2, 3);
        $timestramp = $time[1] . $time2;
        echo 'logdebug->timeGen()->$timestramp:' . $time[1] . $time2;
        echo '</br>';
        return $time[1] . $time2;
    }
    function tilNextMillis($lastTimestamp) {
        $timestamp = $this->timeGen();
        while ($timestamp <= $lastTimestamp) {
            $timestamp = $this->timeGen();
        }
        echo 'logdebug->tilNextMillis()->$timestamp:' . $timestamp;
        echo '</br>';
        return $timestamp;
    }
    function nextId() {
        $timestamp = $this->timeGen();
        echo 'logdebug->nextId()->self::$lastTimestamp1:' . self::$lastTimestamp;
        echo '</br>';
        if (self::$lastTimestamp == $timestamp) {
            self::$sequence = (self::$sequence + 1) & self::$sequenceMask;
            if (self::$sequence == 0) {
                echo "###########" . self::$sequenceMask;
                $timestamp = $this->tilNextMillis(self::$lastTimestamp);
                echo 'logdebug->nextId()->self::$lastTimestamp2:' . self::$lastTimestamp;
                echo '</br>';
            }
        } else {
            self::$sequence = 0;
            echo 'logdebug->nextId()->self::$sequence:' . self::$sequence;
            echo '</br>';
        }
        if ($timestamp < self::$lastTimestamp) {
            throw new Excwption("Clock moved backwards.  Refusing to generate id for " . (self::$lastTimestamp - $timestamp) . " milliseconds");
        }
        self::$lastTimestamp = $timestamp;
        echo 'logdebug->nextId()->self::$lastTimestamp3:' . self::$lastTimestamp;
        echo '</br>';
        echo 'logdebug->nextId()->(($timestamp - self::$twepoch << self::$timestampLeftShift )):' . ((sprintf('%.0f', $timestamp) - sprintf('%.0f', self::$twepoch)));
        echo '</br>';
        $nextId = ((sprintf('%.0f', $timestamp) - sprintf('%.0f', self::$twepoch))) | (self::$workerId << self::$workerIdShift) | self::$sequence;
        echo 'timestamp:' . $timestamp . '-----';
        echo 'twepoch:' . sprintf('%.0f', self::$twepoch) . '-----';
        echo 'timestampLeftShift =' . self::$timestampLeftShift . '-----';
        echo 'nextId:' . $nextId . '----';
        echo 'workId:' . self::$workerId . '-----';
        echo 'workerIdShift:' . self::$workerIdShift . '-----';
        return $nextId;
    }
}
$Idwork = new Idwork(1);
$a = $Idwork->nextId();
$Idwork = new Idwork(2);
$a = $Idwork->nextId();
?>      

 

 

   压力测试结果,8g内存的笔记本,10w次请求1000线程

 

time:0:00:49.145
speed:4069589.9888086272

 

   下面是压力测试的代码

package io.github.id;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.lang3.time.StopWatch;

public class Benchmark {
	public static void main(String[] args) throws InterruptedException {
		Benchmark benchmark = new Benchmark();
		benchmark.test();
	}

	public void test() throws InterruptedException {
		int threadCount = 2000;
		final int genCount = 100000;
		StopWatch watch = new StopWatch();
	    final IdWorker idWorker = new IdWorker(0, 0);
		final CountDownLatch latch = new CountDownLatch(threadCount);
		final  Set<Long> set = new HashSet();
		
		
		watch.start();
		for (int i = 0; i < threadCount; ++i) {
			Thread thread = new Thread() {
				public void run() {
					for (int j = 0; j < genCount; ++j) {
						  long id = idWorker.nextId();
			
			
					}
					latch.countDown();
				}
			};
			thread.start();
		}

		latch.await();
		watch.stop();

		System.err.println("time:" + watch);
		System.err.println("speed:" + genCount * threadCount / (watch.getTime() / 1000.0));
	}
}

 

 
分享到:
评论

相关推荐

    Twitter的分布式自增ID算法snowflake (Java版)

    Twitter的分布式自增ID算法snowflake (Java版)

    Twitter的分布式自增ID雪花算法snowflake

    Twitter的分布式自增ID雪花算法snowflake (Java版)

    Twitter的分布式自增ID算法Snowflake的PHP实现,Snowflake PHP版本,高并发唯一id,全局唯一id,不重复id

    Twitter Snowflake算法,php版代码; 请见博客: http://blog.csdn.net/envon123/article/details/52953872

    snowflake-C语言实现分布式自增有序的唯一ID生成算法

    We have retired the initial release of Snowflake and working on open sourcing the next version based on Twitter-server, in a form that can run anywhere without requiring Twitter's own infrastructure ...

    Java实现Twitter的分布式自增ID算法snowflake

    主要介绍了Java实现Twitter的分布式自增ID算法snowflake,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

    SnowFlake:Twitter的分布式自增ID雪花算法snowflake(Java版)

    而twitter的snowflake解决了这种需求,最初是Twitter把存储系统从MySQL迁移到Cassandra,因为Cassandra没有顺序的ID生成机制,所以开发了这样一套唯一的ID生成服务。结构雪花的结构如下(每部分用-分开): 0 - ...

    Twitter_Snowflake

    Twitter_Snowflake,SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。

    sequence v1.0

    高效GUID产生算法(sequence),基于Snowflake实现64位自增ID算法。新增特性:支持自定义允许时间回拨的范围解决跨毫秒起始值每次为0开始的情况(避免末尾必定为偶数,而不便于取余使用问题)解决高并发场景中获取...

    ID生成器idCreator.zip

    它解决了互联网行业中,使用int自增id或者是string类型的自定义id而导致的 无法方便的分库分表或者是id排序不友好问题。提到id生成器,twitter的snowflake算法 不得不被提起,但是snowflake的算法因为使用了二进制的...

    PHP生成唯一ID之SnowFlake算法

    前言:最近需要做一套CMS系统,由于功能比较单一,而且要求灵活,所以放弃了WP这样的成熟系统,自己做一套相对简单一点的。...最终选择了Twitter的SnowFlake算法 这个算法的好处很简单可以在每秒产生约400W个不同的16位

    SnowflakeIdWorker.java

    * * Twitter_Snowflake ... * * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。

    雪花算法(功能实现全局唯一id)

    SnowFlake 算法,是 Twitter 开源的分布式 id 生成算法。其核心思想就是:使用一个 64 bit 的 long 型的数字作为全局唯一 id。在分布式系统中的应用十分广泛,且ID 引入了时间戳,基本上保持自增的,后面的代码中有...

Global site tag (gtag.js) - Google Analytics