项目中需要一个分布式的Id生成器,twitter的Snowflake中这个既简单又高效,网上找的Java版本

package com.cqfc.id;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* tweeter的snowflake 移植到Java:
* (a) id构成: 42位的时间前缀 + 10位的节点标识 + 12位的sequence避免并发的数字(12位不够用时强制得到新的时间前缀)
* 注意这里进行了小改动: snowkflake是5位的datacenter加5位的机器id; 这里变成使用10位的机器id
* (b) 对系统时间的依赖性非常强,需关闭ntp的时间同步功能。当检测到ntp时间调整后,将会拒绝分配id
*/ public class IdWorker { private final static Logger logger = LoggerFactory.getLogger(IdWorker.class); private final long workerId;
private final long epoch = 1403854494756L; // 时间起始标记点,作为基准,一般取系统的最近时间
private final long workerIdBits = 10L; // 机器标识位数
private final long maxWorkerId = -1L ^ -1L << this.workerIdBits;// 机器ID最大值: 1023
private long sequence = 0L; // 0,并发控制
private final long sequenceBits = 12L; //毫秒内自增位 private final long workerIdShift = this.sequenceBits; //
private final long timestampLeftShift = this.sequenceBits + this.workerIdBits;//
private final long sequenceMask = -1L ^ -1L << this.sequenceBits; // 4095,111111111111,12位
private long lastTimestamp = -1L; private IdWorker(long workerId) {
if (workerId > this.maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", this.maxWorkerId));
}
this.workerId = workerId;
} public synchronized long nextId() throws Exception {
long timestamp = this.timeGen();
if (this.lastTimestamp == timestamp) { // 如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始
this.sequence = this.sequence + 1 & this.sequenceMask;
if (this.sequence == 0) {
timestamp = this.tilNextMillis(this.lastTimestamp);// 重新生成timestamp
}
} else {
this.sequence = 0;
} if (timestamp < this.lastTimestamp) {
logger.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp)));
throw new Exception(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp)));
} this.lastTimestamp = timestamp;
return timestamp - this.epoch << this.timestampLeftShift | this.workerId << this.workerIdShift | this.sequence;
} private static IdWorker flowIdWorker = new IdWorker(1);
public static IdWorker getFlowIdWorkerInstance() {
return flowIdWorker;
} /**
* 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
} /**
* 获得系统当前毫秒数
*/
private static long timeGen() {
return System.currentTimeMillis();
} public static void main(String[] args) throws Exception {
System.out.println(timeGen()); IdWorker idWorker = IdWorker.getFlowIdWorkerInstance();
// System.out.println(Long.toBinaryString(idWorker.nextId()));
System.out.println(idWorker.nextId());
System.out.println(idWorker.nextId());
} }

分布式的Id生成器的更多相关文章

  1. 分布式全局ID生成器设计

    项目是分布式的架构,需要设计一款分布式全局ID,参照了多种方案,博主最后基于snowflake的算法设计了一款自用ID生成器.具有以下优势: 保证分布式场景下生成的ID是全局唯一的 生成的全局ID整体 ...

  2. Jedis使用总结【pipeline】【分布式的id生成器】【分布式锁【watch】【multi】】【redis分布式】(转)

    前段时间细节的了解了Jedis的使用,Jedis是redis的java版本的客户端实现.本文做个总结,主要分享如下内容: [pipeline][分布式的id生成器][分布式锁[watch][multi ...

  3. 分布式唯一id生成器的想法

    0x01 起因 前端时间遇到一个问题,怎么快速生成唯一的id,后来采用了hashid的方法.最近在网上读到了美团关于分布式唯一id生成器的解决方案, 其中提到了三种生成法:(建议看一下这篇文章,写得很 ...

  4. 百度开源的分布式唯一ID生成器UidGenerator,解决了时钟回拨问题

    UidGenerator是百度开源的Java语言实现,基于Snowflake算法的唯一ID生成器.而且,它非常适合虚拟环境,比如:Docker.另外,它通过消费未来时间克服了雪花算法的并发限制.Uid ...

  5. 分布式唯一ID生成器Twitter

    分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的. 有些时候我们希望能使用一种简单一 ...

  6. 分布式全局ID生成器原理剖析及非常齐全开源方案应用示例

    为何需要分布式ID生成器 **本人博客网站 **IT小神 www.itxiaoshen.com **拿我们系统常用Mysql数据库来说,在之前的单体架构基本是单库结构,每个业务表的ID一般从1增,通过 ...

  7. snowflake 分布式唯一ID生成器

    本文来自我的github pages博客http://galengao.github.io/ 即www.gaohuirong.cn 摘要: 原文参考运维生存和开源中国上的代码整理 我的环境是pytho ...

  8. 分布式唯一ID生成器

    在应用程序中,经常需要全局唯一的ID作为数据库主键.如何生成全局唯一ID? 首先,需要确定全局唯一ID是整型还是字符串?如果是字符串,那么现有的UUID就完全满足需求,不需要额外的工作.缺点是字符串作 ...

  9. 分布式ID生成器

    最近会写一篇分布式的ID生成器的文章,先占位.借鉴Mongodb的ObjectId的生成: 4byte时间戳 + 3byte机器标识 + 2byte PID + 3byte自增id 简单代码: imp ...

随机推荐

  1. [LeetCode] Minimum Window Substring 最小窗口子串

    Given a string S and a string T, find the minimum window in S which will contain all the characters ...

  2. 一个简单的ASP.NET MVC异常处理模块

    一.前言 异常处理是每个系统必不可少的一个重要部分,它可以让我们的程序在发生错误时友好地提示.记录错误信息,更重要的是不破坏正常的数据和影响系统运行.异常处理应该是一个横切点,所谓横切点就是各个部分都 ...

  3. JavaScript 属性类型(数据属性和访问器属性)

    数据属性 数据属性包含一个数据值的位置.在这个位置可以读取和写入值.数据属性有 4 个描述其行为的特性. [[Configurable]]:表示能否通过 delete 删除属性从而重新定义属性,能否修 ...

  4. 实体类和DataTable的转换

    引子 最近在项目中在数据库查询的时间,总是要用到数据表到实体类对象列表的转化,自己封装了一个转换的方法,用起来还比较方便,记下来,以后可以重复使用,原理就主要是利用反射,当然有更好的ORM框架可以实现 ...

  5. go database/sql sql-driver/mysql 操作

    这里使用的是github.com/Go-SQL-Driver/MySQL, 所以需要下载一个github.com/Go-SQL-Driver/MySQL 引入 database/sql 和 githu ...

  6. C#-WebForm-文件上传-FileUpload控件

    FileUpload - 选择文件,不能执行上传功能,通过点击按钮实现上传 默认选择类型为所有类型 //<上传>按钮 void Button1_Click(object sender, E ...

  7. cocos2d-x 3.5以后版本的 luasocket

    cocos2d-x 3.5后使用luasocket:local SOCKET = require "socket"; 结果运行就报错:[LUA-print] USE " ...

  8. NSRunLoop的进一步理解

    iPhone应用开发中关于NSRunLoop的概述是本文要介绍的内容,NSRunLoop是一种更加高明的消息处理模式,他就高明在对消息处理过程进行了更好的抽象和封装,这样才能是的你不用处理一些很琐碎很 ...

  9. 深入浅出 Redis client/server交互流程

    综述 最近笔者阅读并研究redis源码,在redis客户端与服务器端交互这个内容点上,需要参考网上一些文章,但是遗憾的是发现大部分文章都断断续续的非系统性的,不能给读者此交互流程的整体把握.所以这里我 ...

  10. Linux下查看chm文件

    第一种方法.安装xchm,安装命令sudo apt-get install xchm,打开xchm,在终端下输入xchm. 第二种方法.安装kchmviewer,安装命令sudo apt-get in ...