MyBatis-Plus主键策略(雪花算法16位长度的整型id,解决默认雪花算法生成19位长度id导致JS精度丢失问题)
js表达的最大整数长度为16位,精度丢失后面几位全是0!
解决方案:
16位长度的long整型id示例
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
@Component
public class CustomerIdGenerator implements IdentifierGenerator {
@Override
public Long nextId(Object entity) {
return IdGenerator.generateId();
}
}
import java.util.Date;
import java.util.UUID;
public class IdGenerator {
private static IdGenerator instance = new IdGenerator(0);
public static IdGenerator initDefaultInstance(int machineId) {
instance = new IdGenerator(machineId);
return instance;
}
public static IdGenerator getInstance() {
return instance;
}
public static long generateId() {
return instance.nextId();
}
private final static long MACHINE_BIT = 5;
private final static long SEQUENCE_BIT = 8;
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long TIMESTMP_LEFT = MACHINE_BIT + SEQUENCE_BIT;
private long machineId;
private long sequence = 0L;
private long lastStmp = -1L;
private IdGenerator(long machineId) {
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException(
"machineId can't be greater than " + MAX_MACHINE_NUM + " or less than 0");
}
this.machineId = machineId;
}
public synchronized long nextId() {
long currStmp = getTimestamp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStmp == lastStmp) {
sequence = (sequence + 1) & MAX_SEQUENCE;
if (sequence == 0L) {
currStmp = getNextTimestamp();
}
} else {
sequence = 0L;
}
lastStmp = currStmp;
return currStmp << TIMESTMP_LEFT
| machineId << MACHINE_LEFT
| sequence;
}
private long getNextTimestamp() {
long mill = getTimestamp();
while (mill <= lastStmp) {
mill = getTimestamp();
}
return mill;
}
private long getTimestamp() {
return System.currentTimeMillis() / 10;
}
public static Date parseIdTimestamp(long id) {
return new Date((id >>> TIMESTMP_LEFT) * 10);
}
public static String uuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
}