文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java生成UUID的常用方式

2023-09-03 18:49

关注
  1. java.util.UUID类来生成UUID

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());    }}

  1. Apache Commons IO库中的UUIDUtils类

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);    }}
  1. 使用Google Guice库中的UUIDGenerator类生成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());    }}
  1. 使用JDK的MessageDigest类和SecureRandom类:可以通过Hash算法和随机数生成UUID

写法一: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;    }}
  1. 使用Snowflake算法生成UUID

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();    }}
  1. 将时间戳和随机数作为种子生成UUID

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());    }}
  1. 使用Redis集群的redisson框架提供的RUID类生成UUID

import org.redisson.api.RUID;public class UUIDGenerator {    public static void main(String[] args) {        RUID ruid = RUID.randomUID();        System.out.println("生成的UUID为:" + ruid.toString());    }}
  1. 利用SecureRandom类生成

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();    }}

三方库详细版

  1. 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);    }}
  1. Google Guava:

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

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯