IdGenerator、AlternativeJdkIdGenerator、JdkIdGenerator、SimpleIdGenerator

IdGenerator

顶层接口,生成UUID

UUID generateId();

 

 

 

AlternativeJdkIdGenerator 

使用SecureRandom作为初始种子

SecureRandom secureRandom = new SecureRandom();
byte[] seed = new byte[8];
secureRandom.nextBytes(seed);
this.random = new Random(new BigInteger(seed).longValue());

并在其后使用Random生成UUID,相比UUID的randomUUID,在安全的随机ID和性能之间提供了更好的平衡

byte[] randomBytes = new byte[16];
this.random.nextBytes(randomBytes);

long mostSigBits = 0;
for (int i = 0; i < 8; i++) {
mostSigBits = (mostSigBits << 8) | (randomBytes[i] & 0xff);
}

long leastSigBits = 0;
for (int i = 8; i < 16; i++) {
leastSigBits = (leastSigBits << 8) | (randomBytes[i] & 0xff);
}

return new UUID(mostSigBits, leastSigBits);

 

JdkIdGenerator

使用UUID.randomUUID

 

SimpleIdGenerator

使用UUID的构造方法从1开始递增到Long.MAX_VALUE后再循环

return new UUID(0, this.leastSigBits.incrementAndGet());

 

posted on 2021-10-07 15:46  icodegarden  阅读(232)  评论(0编辑  收藏  举报