JS的數字類型目前支持的最大值為:9007199254740992,一旦數字超過這個值,JS將會丟失精度,導致前后端的值出現不一致。
JAVA的Long類型的 最大值為:9223372036854775807,snowflake的算法在實現上確實沒問題的,但實際運用的時候一定要避免這個潛在的深坑。
有個博友遇到這個問題的解決方案:
https://www.cnblogs.com/do-your-best/p/9443342.html
mybatis plus的解決方案:
https://mp.baomidou.com/guide/faq.html#id-worker-生成主鍵太長導致-js-精度丟失
snowflake算法的java實現版本參考:
import lombok.extern.slf4j.Slf4j; /** * id構成: 42位的時間前綴 + 10位的節點標識 + 12位的sequence避免並發的數字(12位不夠用時強制得到新的時間前綴) */ @Slf4j public class IdWorker { /** * 時間起始標記點,作為基准,一般取系統的最近時間 * 此處以2018-01-01為基准時間 */ private final long epoch = 1514736000000L; /** * 機器標識位數 */ private final long workerIdBits = 4L; /** * 毫秒內自增位 */ private final long sequenceBits = 12L; /** * 機器ID最大值:16 */ private final long maxWorkerId = -1L ^ -1L << this.workerIdBits; private final long workerIdShift = this.sequenceBits; private final long timestampLeftShift = this.sequenceBits + this.workerIdBits; private final long sequenceMask = -1L ^ -1L << this.sequenceBits; private final long workerId; /** * 並發控制 */ private long sequence = 0L; private long lastTimestamp = -1L; public 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() { long timestamp = this.currentTimeMillis(); if (this.lastTimestamp == timestamp) { // 如果上一個timestamp與新產生的相等,則sequence加一(0-4095循環); // 對新的timestamp,sequence從0開始 this.sequence = this.sequence + 1 & this.sequenceMask; if (this.sequence == 0) { // 重新生成timestamp timestamp = this.tilNextMillis(this.lastTimestamp); } } else { this.sequence = 0; } if (timestamp < this.lastTimestamp) { throw new RuntimeException( 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; } /** * 等待下一個毫秒的到來, 保證返回的毫秒數在參數lastTimestamp之后 */ private long tilNextMillis(long lastTimestamp) { long timestamp = this.currentTimeMillis(); while (timestamp <= lastTimestamp) { timestamp = this.currentTimeMillis(); } return timestamp; } /** * 獲得系統當前毫秒數 */ private long currentTimeMillis() { return System.currentTimeMillis(); } public static void main(String[] args) { System.out.println(Long.MAX_VALUE); } }
上面的代碼是一個全局的synchronized,如果一個服務里涉及到多個表,而這些表的ID其實可以相互重復的,那么都從同一個生成器里獲取nextId的話將導致鎖競爭比較激烈,從而導致效率變低,解決方案有:
1、建立多個針對不同表的這個生成器
2、在方法里的入參里加入業務放/表參數,然后使用synchronized塊。
