分布式全域性ID之雪花演算法

2021-09-11 13:53:14 字數 1970 閱讀 8135

public class idworker 

if (datacenterid > maxdatacenterid || datacenterid < 0)

system.out.printf(

"worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d",

timestampleftshift, datacenteridbits, workeridbits, sequencebits, workerid);

this.workerid = workerid;

this.datacenterid = datacenterid;

this.sequence = sequence;

}private long twepoch = 1288834974657l;

private long workeridbits = 5l;

private long datacenteridbits = 5l;

// 這個是二進位制運算,就是 5 bit最多只能有31個數字,也就是說機器id最多只能是32以內

private long maxworkerid = -1l ^ (-1l << workeridbits);

// 這個是乙個意思,就是 5 bit最多只能有31個數字,機房id最多只能是32以內

private long maxdatacenterid = -1l ^ (-1l << datacenteridbits);

private long sequencebits = 12l;

private long workeridshift = sequencebits;

private long datacenteridshift = sequencebits + workeridbits;

private long timestampleftshift = sequencebits + workeridbits + datacenteridbits;

private long sequencemask = -1l ^ (-1l << sequencebits);

private long lasttimestamp = -1l;

public long getworkerid()

public long getdatacenterid()

public long gettimestamp()

public synchronized long nextid()

if (lasttimestamp == timestamp)

} else

// 這兒記錄一下最近一次生成id的時間戳,單位是毫秒

lasttimestamp = timestamp;

// 這兒就是將時間戳左移,放到 41 bit那兒;

// 將機房 id左移放到 5 bit那兒;

// 將機器id左移放到5 bit那兒;將序號放最後12 bit;

// 最後拼接起來成乙個 64 bit的二進位制數字,轉換成 10 進製就是個 long 型

return ((timestamp - twepoch) << timestampleftshift) | (datacenterid << datacenteridshift)

| (workerid << workeridshift) | sequence;

}private long tilnextmillis(long lasttimestamp)

return timestamp;

}private long timegen()

// ---------------測試---------------

public static void main(string args)

}}

SnowFlakeId 分布式雪花id演算法

package com.jn.baseservice.utils import com.jn.baseservice.common.number import lombok.getter import lombok.setter import lombok.extern.log4j.log4j2 i...

雪花演算法生成分布式ID

package top.sponger.common.util import lombok.data 描述 twitter的分布式自增id雪花演算法snowflake public class snowflake if machineid max machine num machineid 0 th...

分布式ID生成方式之雪花演算法

在資料量不大的情況下,單庫單錶完全滿足現有業務,但是隨著資料日益增大,分庫分表是必然的操作,這時候繼續用資料庫的自增id無法滿足需求,因為假如有多張表都是存訂單的資訊,每個表都是自增的id,那就會出現重複的id號了,當然可以設定表的步長,比如表1的id從1開始,每隔兩步增長一次。表2的id從2開始,...