/**
* Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
*
* The {@code UUID} is generated using a cryptographically strong pseudo
* random number generator.
*
* @return A randomly generated {@code UUID}
*/publicstatic UUID randomUUID(){
SecureRandom ng = Holder.numberGenerator;byte[] randomBytes =newbyte[16];
ng.nextBytes(randomBytes);
randomBytes[6]&=0x0f;/* clear version */
randomBytes[6]|=0x40;/* set to version 4 */
randomBytes[8]&=0x3f;/* clear variant */
randomBytes[8]|=0x80;/* set to IETF variant */returnnewUUID(randomBytes);}/*
* Private constructor which uses a byte array to construct the new UUID.
*/privateUUID(byte[] data){long msb =0;long lsb =0;assert data.length ==16:"data must be 16 bytes in length";for(int i=0; i<8; i++)
msb =(msb <<8)|(data[i]&0xff);for(int i=8; i<16; i++)
lsb =(lsb <<8)|(data[i]&0xff);this.mostSigBits = msb;this.leastSigBits = lsb;}
Spring Core自定义的UUID生成器
package org.springframework.util;import java.math.BigInteger;import java.security.SecureRandom;import java.util.Random;import java.util.UUID;publicclassAlternativeJdkIdGeneratorimplementsIdGenerator{privatefinal Random random;publicAlternativeJdkIdGenerator(){
SecureRandom secureRandom =newSecureRandom();byte[] seed =newbyte[8];
secureRandom.nextBytes(seed);this.random =newRandom(newBigInteger(seed).longValue());}@Overridepublic UUID generateId(){byte[] randomBytes =newbyte[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);}returnnewUUID(mostSigBits, leastSigBits);}}