关于snowflake算法生成的ID转换为JS的数字类型由于过大导致JS精度丢失的问题
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块。