李锋镝的博客

  • 首页
  • 时间轴
  • 评论区显眼包🔥
  • 左邻右舍
  • 博友圈
  • 关于我
    • 关于我
    • 另一个网站
    • 我的导航站
    • 网站地图
    • 赞助
  • 留言
  • 🚇开往
Destiny
自是人生长恨水长东
  1. 首页
  2. 原创
  3. 正文

UUID太长怎么办?快来试试NanoId

2022年3月31日 264点热度 0人点赞 2条评论

什么是NanoId

nanoid库和uuid库一样都可以生成唯一识别码,但是nanoid相比uuid要更轻量级。

用法

可以引用下方的jar包,或者项目中直接自己创建工具类。

引用jar包的POM依赖如下:

        <dependency>
            <groupId>com.aventrix.jnanoid</groupId>
            <artifactId>jnanoid</artifactId>
            <version>2.0.0</version>
        </dependency>

工具类源码如下:

import java.security.SecureRandom;
import java.util.Random;

public final class NanoIdUtils {
    public static final SecureRandom DEFAULT_NUMBER_GENERATOR = new SecureRandom();
    public static final char[] DEFAULT_ALPHABET = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    public static final int DEFAULT_SIZE = 21;

    private NanoIdUtils() {
    }

    public static String randomNanoId() {
        return randomNanoId(DEFAULT_NUMBER_GENERATOR, DEFAULT_ALPHABET, 21);
    }

    public static String randomNanoId(Random random, char[] alphabet, int size) {
        if (random == null) {
            throw new IllegalArgumentException("random cannot be null.");
        } else if (alphabet == null) {
            throw new IllegalArgumentException("alphabet cannot be null.");
        } else if (alphabet.length != 0 && alphabet.length < 256) {
            if (size <= 0) {
                throw new IllegalArgumentException("size must be greater than zero.");
            } else {
                int mask = (2 << (int)Math.floor(Math.log((double)(alphabet.length - 1)) / Math.log(2.0D))) - 1;
                int step = (int)Math.ceil(1.6D * (double)mask * (double)size / (double)alphabet.length);
                StringBuilder idBuilder = new StringBuilder();

                while(true) {
                    byte[] bytes = new byte[step];
                    random.nextBytes(bytes);

                    for(int i = 0; i < step; ++i) {
                        int alphabetIndex = bytes[i] & mask;
                        if (alphabetIndex < alphabet.length) {
                            idBuilder.append(alphabet[alphabetIndex]);
                            if (idBuilder.length() == size) {
                                return idBuilder.toString();
                            }
                        }
                    }
                }
            }
        } else {
            throw new IllegalArgumentException("alphabet must contain between 1 and 255 symbols.");
        }
    }
}

工具类使用Demo

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(NanoIdUtils.randomNanoId());
            System.out.println(UUID.randomUUID());
        }
    }

输出:

tDT8gsr4aVwOvV10Pv6gX
1cc2ed01-4806-4698-96fb-2b2a1f255f9d
bzB0HMTxz18tWKTAMfyw_
33d63b00-b622-4302-a9ff-a1dd0033da42
6O7RE6YYNr1r_pn0ONhDR
53619651-fc19-4040-b0ab-b2f4a44c2641
bT9iJzMBsuXTJP2f559rE
7ffff372-fe0b-4dc9-8f96-76d3232ff3a9
FVHs5eoEPaPWWIgEqy0E1
90530a13-3ba3-4cf6-8a16-df66fc58ad53
aSmAG2am1dVZqVxDPXZ7C
c92aa977-e6df-4e8a-adc1-6edcf8ad8e23
oPKD5D76UNJabUYK-1mDS
ff087591-7011-49b8-8e3e-d9a3d62721db
0yZ9ej7rw0MGarryS_lZx
39abd8b9-72a8-4b66-8236-c3e83c3e1ba4
B6EgZgE0o49i2iPcFdR9J
08ff3204-b74b-448b-b1a5-041e31d503b9
GnouvvsCoYlEBw9IAZNLF
0da3b34a-87a7-4316-8f2a-5b4f6cf5a24f
除非注明,否则均为李锋镝的博客原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.lifengdi.com/article/3794

相关文章

  • CompletableFuture使用详解
  • JAVA之从线程安全说到锁
  • ReentrantLock深度解析
  • SpringBoot常用注解
  • 金融级JVM深度调优实战的经验和技巧
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: JAVA 高并发
最后更新:2022年3月31日

李锋镝

既然选择了远方,便只顾风雨兼程。

打赏 点赞
< 上一篇
下一篇 >

文章评论

  • 哥斯拉白银

    有win下的相关项目吗?生成稳定硬件码的。

    Windows
    Chrome 90.0.4430.212 美国-Washington
    2022年4月1日
    回复
    • 李锋镝大师

      @哥斯拉 没有 哈哈

      Windows
      Chrome 99.0.4844.51 中国-北京
      2022年4月1日
      回复
  • 1 2 3 4 5 6 7 8 9 11 12 13 14 15 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 57 58 60 61 62 63 64 65 66 67 69 72 74 76 77 78 79 80 81 82 85 86 87 90 92 93 94 95 96 97 98 99
    取消回复

    愿将腰下剑,直为斩楼兰。

    那年今日(04月20日)

    • 1971年:中国著名法学家周鲠生逝世
    • 1901年:著名建筑学家梁思成出生于日本东京,祖籍广东新会
    • 1889年:德国纳粹党元首希特勒出生于奥地利布劳瑙
    • 1808年:法兰西第二帝国皇帝拿破仑出生
    • 429年:中国古代数学家祖冲之出生
    • 更多历史事件
    最新 热点 随机
    最新 热点 随机
    Everything Claude Code 详细使用文档 配置Jackson使用字段而不是getter/setter来序列化和反序列化 这个域名注册整整十年了,十年时间,真快啊 Claude Code全维度实战指南:从入门到精通,解锁AI编程新范式 Apollo配置中心中的protalDB的作用是什么 org.apache.ibatis.plugin.Interceptor类详细介绍及使用
    AI时代,个人技术博客的出路在哪里?使用WireGuard在Ubuntu 24.04系统搭建VPN这个域名注册整整十年了,十年时间,真快啊WordPress实现用户评论等级排行榜插件WordPress网站换了个字体,差点儿把样式换崩了做了一个WordPress文章热力图插件
    使用WireGuard在Ubuntu 24.04系统搭建VPN 为什么 Apache Doris 是比 Elasticsearch 更好的实时分析替代方案? 妹妹的画【2019.07.03】 jmap命令(jdk1.8) 我要狠狠的反驳“公司禁止使用 Lombok ”的观点! Java之五种遍历Map集合的方式
    标签聚合
    SpringBoot 多线程 分布式 AI docker 数据库 AI编程 ElasticSearch Redis Spring JVM 设计模式 WordPress IDEA SQL JAVA 架构 日常 MySQL K8s
    友情链接
    • Blogs·CN
    • Honesty
    • Mr.Sun的博客
    • 临窗旋墨
    • 哥斯拉
    • 彬红茶日记
    • 志文工作室
    • 懋和道人
    • 拾趣博客导航
    • 搬砖日记
    • 旧时繁华
    • 林羽凡
    • 瓦匠个人小站
    • 皮皮社
    • 知向前端
    • 蜗牛工作室
    • 韩小韩博客
    • 风渡言

    COPYRIGHT © 2026 lifengdi.com. ALL RIGHTS RESERVED.

    域名年龄

    Theme Kratos Made By Dylan

    津ICP备2024022503号-3

    京公网安备11011502039375号