import java.util.UUID;public class UUIDGenerator { public static void main(String[] args) { //随机生成一个UUID对象 UUID uuid = UUID.randomUUID(); System.out.println("生成的UUID为:" + uuid.toString()); //通过给定的字符串名称和命名空间生成UUID对象 UUID uuid2 = UUID.nameUUIDFromBytes("example_name".getBytes()); System.out.println("生成的UUID2为:" + uuid2.toString()); }}
import org.apache.commons.io.UUIDUtils;public class UUIDGenerator { public static void main(String[] args) { //随机生成一个UUID字符串 String uuid = UUIDUtils.randomUUID().toString(); System.out.println("生成的UUID为:" + uuid); }}
import com.google.inject.Inject;import com.google.inject.name.Named;import java.util.UUID;public class UUIDGenerator { private final UUID uuid; @Inject public UUIDGenerator(@Named("randomUUID") UUID uuid) { this.uuid = uuid; } public UUID getUUID() { return uuid; } public static void main(String[] args) { UUIDGenerator generator = new UUIDGenerator(UUID.randomUUID()); System.out.println("生成的UUID为:" + generator.getUUID().toString()); }}
写法一:import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.util.UUID;public class UUIDGenerator { public static void main(String[] args) throws NoSuchAlgorithmException { SecureRandom secureRandom = new SecureRandom(); byte[] seed = secureRandom.generateSeed(16); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(seed); UUID uuid = UUID.nameUUIDFromBytes(md5.digest()); System.out.println("生成的UUID为:" + uuid.toString()); }}写法二:import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.Random;public class UUIDGenerator { public static String generateUUID() { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest((System.currentTimeMillis() + new Random().nextInt(99999999) + "").getBytes()); StringBuilder sb = new StringBuilder(); for (byte b : messageDigest) { sb.append(String.format("%02x", b)); } result = sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }}
Snowflake算法是Twitter开源的分布式ID生成算法,可以在多个节点上生成唯一的ID
import com.github.f4b6a3.uuid.UuidCreator;import com.github.f4b6a3.uuid.enums.UuidVariant;import com.github.f4b6a3.uuid.enums.UuidVersion;import com.github.f4b6a3.uuid.impl.TimeBasedUuidCreator;import java.time.Instant;public class UUIDGenerator { public static void main(String[] args) { UuidCreator creator = TimeBasedUuidCreator.withRandomNodeId(); Instant now = Instant.now(); long timestamp = now.getEpochSecond() * 1000 + now.getNano() / 1000000; String uuid = creator.create(UuidVersion.VERSION_TIME_BASED, timestamp).toString(); System.out.println("生成的UUID为:" + uuid); }}
Snowflake算法第二种:
public class UUIDGenerator { private final long twepoch = 1483200000000L; private final long workerIdBits = 5L; private final long datacenterIdBits = 5L; private final long maxWorkerId = -1L ^ (-1L << workerIdBits); private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); private final long sequenceBits = 12L; private final long workerIdShift = sequenceBits; private final long datacenterIdShift = sequenceBits + workerIdBits; private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; private final long sequenceMask = -1L ^ (-1L << sequenceBits); private long workerId = 0L; private long datacenterId = 0L; private long sequence = 0L; private long lastTimestamp = -1L; public UUIDGenerator(long workerId, long datacenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; } public synchronized long nextId() { long timestamp = timeGen(); // 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过,此时应当抛出异常 if (timestamp < lastTimestamp) { throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } // 如果是同一时间生成的,则进行毫秒内序列 if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; // 毫秒内序列溢出 if (sequence == 0) { // 阻塞到下一个毫秒,获得新的时间戳 timestamp = tilNextMillis(lastTimestamp); } } // 时间戳改变,毫秒内序列重置 else { sequence = 0L; } // 上次生成ID的时间截 lastTimestamp = timestamp; // 移位并通过或运算拼到一起组成64位的ID return ((timestamp - twepoch) << timestampLeftShift) // | (datacenterId << datacenterIdShift) // | (workerId << workerIdShift) // | sequence; } protected long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } protected long timeGen() { return System.currentTimeMillis(); }}
import java.util.UUID;public class UUIDGenerator { public static void main(String[] args) { long time = System.currentTimeMillis(); int random = (int) (Math.random() * Integer.MAX_VALUE); UUID uuid = new UUID(time, random); System.out.println("生成的UUID为:" + uuid.toString()); }}
import org.redisson.api.RUID;public class UUIDGenerator { public static void main(String[] args) { RUID ruid = RUID.randomUID(); System.out.println("生成的UUID为:" + ruid.toString()); }}
import java.security.SecureRandom;import java.util.UUID;public class UUIDGenerator { public static String generateUUID() { return UUID.randomUUID().toString(); } public static String generateSecureUUID() { SecureRandom random = new SecureRandom(); byte[] bytes = new byte[16]; random.nextBytes(bytes); return UUID.nameUUIDFromBytes(bytes).toString(); }}
三方库详细版
- Apache Commons:
引入以下Maven依赖
<dependency> <groupId>commons-langgroupId> <artifactId>commons-langartifactId> <version>2.6version>dependency>
java示例代码:
import org.apache.commons.lang3.StringUtils;import java.util.UUID;public class GenerateUUID { public static void main(String[] args) { UUID uuid = UUID.randomUUID(); String uuidStr = StringUtils.remove(uuid.toString(), '-'); System.out.println("UUID:" + uuidStr); }}
Google Guava库可以使用它的UUID类来生成UUID。需要引入以下Maven依赖:
<dependency> <groupId>com.google.guavagroupId> <artifactId>guavaartifactId> <version>30.0-jreversion>dependency>
java示例:
import com.google.common.base.CharMatcher;import java.util.UUID;public class GenerateUUID { public static void main(String[] args) { UUID uuid = UUID.randomUUID(); String uuidStr = CharMatcher.is('-').removeFrom(uuid.toString()); System.out.println("UUID:" + uuidStr); }}
注意事项
之前提到了 Apache Commons 的 UUIDUtils 工具类,但是这个工具类实际上是用于字符串格式与 UUID 转化的,而不是生成 UUID。
如果你想要使用 Apache Commons 中的工具类来生成 UUID ,可以使用 RandomStringUtils 类中的 randomUUID() 方法。下面是一个简单示例:
import org.apache.commons.lang3.RandomStringUtils;public class GenerateUUID { public static void main(String[] args) { String uuid = RandomStringUtils.randomNumeric(8) + "-" + RandomStringUtils.randomNumeric(4) + "-" + RandomStringUtils.randomNumeric(4) + "-" + RandomStringUtils.randomNumeric(4) + "-" + RandomStringUtils.randomNumeric(12); System.out.println("UUID:" + uuid); }}
来源地址:https://blog.csdn.net/qq_45699990/article/details/129814826