您的位置:首页 > 其它

高并发环境下生成订单唯一流水号方法:SnowFlake

2017-11-24 15:14 337 查看

业务需求:

订单号不能重复

订单号没有规则,即编码规则不能加入任何和公司运营相关的数

据,外部人员无法通过订单ID猜测到订单量。不能被遍历。

订单号长度固定,且不能太长

易读,易沟通,不要出现数字字母换乱现象

生成耗时

关于订单号的生成,一些比较简单的方案:

数据库自增长ID

优势:无需编码

缺陷:

大表不能做水平分表,否则插入删除时容易出现问题

高并发下插入数据需要加入事务机制

在业务操作父、子表(关联表)插入时,先要插入父表,再插入子表

时间戳+随机数

优势:编码简单

缺陷:随机数存在重复问题,即使在相同的时间戳下。每次插入数据库前需要校验下是否已经存在相同的数值。

时间戳+会员ID

优势:同一时间,一个用户不会存在两张订单

缺陷:会员ID也会透露运营数据,鸡生蛋,蛋生鸡的问题

GUID/UUID

优势:简单

劣势:用户不友好,索引关联效率较低。

今天要分享的方案:来自twitter的SnowFlake

Twitter-Snowflake算法产生的背景相当简单,为了满足Twitter每秒上万条消息的请求,每条消息都必须分配一条唯一的id,这些id还需要一些大致的顺序(方便客户端排序),并且在分布式系统中不同机器产生的id必须不同.Snowflake算法核心把时间戳,工作机器id,序列号(毫秒级时间41位+机器ID 10位+毫秒内序列12位)组合在一起。



在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间,然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识),然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。

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

详细参考:https://www.biaodianfu.com/snowflake.html

import java.math.BigInteger;
/**
* 42位的时间前缀+10位的节点标识+12位的sequence避免并发的数字(12位不够用时强制得到新的时间前缀)
* <p>
* <b>对系统时间的依赖性非常强,需要关闭ntp的时间同步功能,或者当检测到ntp时间调整后,拒绝分配id。
*
* @author sumory.wu
* @date 2012-2-26 下午6:40:28
*/
public class IdWorker {

private final long workerId;
private final long snsEpoch = 1330328109047L;// 起始标记点,作为基准
private long sequence = 0L;// 0,并发控制
private final long workerIdBits = 10L;// 只允许workid的范围为:0-1023
private final long maxWorkerId = -1L ^ -1L << this.workerIdBits;// 1023,1111111111,10位
private final long sequenceBits = 12L;// sequence值控制在0-4095

private final long workerIdShift = this.sequenceBits;// 12
private final long timestampLeftShift = this.sequenceBits + this.workerIdBits;// 22
private final long sequenceMask = -1L ^ -1L << this.sequenceBits;// 4095,111111111111,12位

private long lastTimestamp = -1L;

public IdWorker(long workerId) {
super();
if (workerId > this.maxWorkerId || workerId < 0) {// workid < 1024[10位:2的10次方]
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循环),下次再使用时sequence是新值
//System.out.println("lastTimeStamp:" + lastTimestamp);
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) {
System.out.println("Clock moved backwards.Refusing to generate id for "+(t
4000
his.lastTimestamp - timestamp)+"milliseconds.");
throw new Exception(String.format("Clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp)));
}

this.lastTimestamp = timestamp;
// 生成的timestamp
return timestamp - this.snsEpoch << this.timestampLeftShift | this.workerId << this.workerIdShift | this.sequence;
}

/**
* 保证返回的毫秒数在参数之后
*
* @param lastTimestamp
* @return
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}

/**
* 获得系统当前毫秒数
*
* @return
*/
private long timeGen() {
return System.currentTimeMillis();
}

public static void main(String[] args) throws Exception {
IdWorker iw1 = new IdWorker(1);
IdWorker iw2 = new IdWorker(2);
IdWorker iw3 = new IdWorker(3);

// System.out.println(iw1.maxWorkerId);
// System.out.println(iw1.sequenceMask);

System.out.println("---------------------------");

long workerId = 1L;
long twepoch = 1330328109047L;
long sequence = 0L;// 0
long workerIdBits = 10L;
long maxWorkerId = -1L ^ -1L << workerIdBits;// 1023,1111111111,10位
long sequenceBits = 12L;

long workerIdShift = sequenceBits;// 12
long timestampLeftShift = sequenceBits + workerIdBits;// 22
long sequenceMask = -1L ^ -1L << sequenceBits;// 4095,111111111111,12位

long ct = System.currentTimeMillis();// 1330328109047L;//
System.out.println(ct);

System.out.println(ct - twepoch);
System.out.println(ct - twepoch << timestampLeftShift);// 左移22位:*2的22次方
System.out.println(workerId << workerIdShift);// 左移12位:*2的12次方
System.out.println("哈哈");
System.out.println(ct - twepoch << timestampLeftShift | workerId << workerIdShift);
long result = ct - twepoch << timestampLeftShift | workerId << workerIdShift | sequence;// 取时间的低40位 | (小于1024:只有12位)的低12位 | 计算的sequence
System.out.println(result);

System.out.println("---------------");
for (int i = 0; i < 10; i++) {
System.out.println("IdWorker 01:"+iw1.nextId());
System.out.println("IdWorker 02:"+iw2.nextId());
System.out.println("IdWorker 03:"+iw3.nextId());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: