UUID太长怎么办?快来试试NanoId(Java版本)

毋城
2023-12-01

一、什么是NanoId

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

二、怎么使用

引入jar包或使用工具类

 <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.");
        }
    }
}

三、初体验

public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(NanoIdUtils.randomNanoId());
            System.out.println(UUID.randomUUID());
        }
    }
DHxVDk6OlUpJv4DMsJBQm
f6a4834d-494d-411f-98c6-aae886d104ec
OITlZuemCDn9CRR0ZruMB
0990b182-127a-44f7-9660-5bf9e8fb232f
GNNdtQaXVCRYgfxPbr1TF
8de0a3f9-5db1-43a9-806f-be95084586d2
BXpOVuLkOGdiu6bwxV34i
c9dbfdab-11a0-454c-b700-55f3556c5335
KB8kXivS0urYqnx_Hs1vp
36775a12-bed3-47f4-b9d9-eecb156079fa
nuTskLmIof63GExt9sduR
b448109f-bad9-473c-a1c5-f3a65f80a698
pJRdALwVBlrVMSuKwEX_z
e252312e-3806-4581-b3b4-842cccf83298
LuH50GGpZGqQz4ny2F7wT
01b846b0-753b-4fcf-97bd-c19bd2368570
qBndTEU1n2KBslPqORc67
a2f828cc-b5cf-4639-b2fe-e674ae0db4b5
vbNaVYd6rqUfbEWpcxrKM
321cc407-e72f-434f-89ce-06c6eec3ff88

四、相比优势

[译] 为什么 NanoID 会取代 UUID - 知乎

空间小、更安全、可以自动以子母表

 类似资料: