import cn.hutool.core.date.SystemClock;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import java.util.*;
public static void main(String[] args) {
//生成字符串随机数id
UUID uuid = UUID.randomUUID();
System.out.println(uuid);//a0f61136-19a2-4cbb-8c41-c2cb7f734131
//生成long类型 的id
DefaultIdentifierGenerator defaultIdentifierGenerator = new DefaultIdentifierGenerator();
Long aLong = defaultIdentifierGenerator.nextId(new Object().toString());
System.out.println(aLong);//1602296057001435137
}
//defaultIdentifierGenerator对象的nextId 方法 底层 源码
public synchronized long nextId() {
//通过timeGen() 方法获取当前毫米值
long timestamp = this.timeGen();
//lastTimestamp 初始化后的值 为-1
if (timestamp < this.lastTimestamp) {
//当获取的当前时间小于lastTimestamp 时间时 求取增量
long offset = this.lastTimestamp - timestamp;
if (offset > 5L) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", offset));
}
try {
this.wait(offset << 1);
timestamp = this.timeGen();
if (timestamp < this.lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", offset));
}
} catch (Exception var6) {
throw new RuntimeException(var6);
}
}
if (this.lastTimestamp == timestamp) {
this.sequence = this.sequence + 1L & 4095L;
if (this.sequence == 0L) {
timestamp = this.tilNextMillis(this.lastTimestamp);
}
} else {
this.sequence = ThreadLocalRandom.current().nextLong(1L, 3L);
}
//将获取的当前毫秒值进行赋值
this.lastTimestamp = timestamp;
//对返回值 进行一些运算
return timestamp - 1288834974657L << 22 | this.datacenterId << 17 | this.workerId << 12 | this.sequence;
}
//获取当前系统时间 方法
protected long timeGen() {
//获取当前时间方法 为什么 不使用 System.currentTimeMillis() 方法呢?
return SystemClock.now();
}
//currentTimeMillis 方法是被 native 所修饰的在并发数量过高时会影响性能
//SystemClock.now(); 是被volatile 所修饰的 保证可见性 不保证原子性 禁止指令重排
public static native long currentTimeMillis();
Java 代码生成字符串Id及Long类型的Id(源码解析)
于 2022-12-12 22:04:47 首次发布