什么是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
除非注明,否则均为李锋镝的博客原创文章,转载必须以链接形式标明本文链接
有win下的相关项目吗?生成稳定硬件码的。
@哥斯拉 没有 哈哈