UUID v7 目前 JDK 有提供实现么?没有的话大家一般用什么第三方 library?

49 天前
 BraveXaiver
谢谢
2520 次点击
所在节点    Java
9 条回复
gxt92
49 天前
Java Uuid Generator (JUG) is a Java library for generating all standard UUID versions (v1 - v7)
https://github.com/cowtowncoder/java-uuid-generator
C02TobNClov1Dz56
49 天前
//这里有个简单的实现, 我也不知道摘抄自哪里了
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.UUID;

/**
* 时间顺序的 UUID
*/
public class UUIDv7 {
private static final SecureRandom random = new SecureRandom();

public static UUID randomUUID() {
byte[] value = randomBytes();
ByteBuffer buf = ByteBuffer.wrap(value);
long high = buf.getLong();
long low = buf.getLong();
return new UUID(high, low);
}

private static byte[] randomBytes() {
// random bytes
byte[] value = new byte[16];
random.nextBytes(value);

// current timestamp in ms
ByteBuffer timestamp = ByteBuffer.allocate(Long.BYTES);
timestamp.putLong(System.currentTimeMillis());

// timestamp
System.arraycopy(timestamp.array(), 2, value, 0, 6);

// version and variant
value[6] = (byte) ((value[6] & 0x0F) | 0x70);
value[8] = (byte) ((value[8] & 0x3F) | 0x80);

return value;
}

// public static void main(String[] args) {
// UUID uuid = UUIDv7.randomUUID();
// System.out.println(uuid);
// }
}
C02TobNClov1Dz56
49 天前
billbob
49 天前
asd999cxcx
49 天前
我个人现在一般用 nanoId
hideon
49 天前
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
<version>5.1.0</version>
</dependency>
hideon
49 天前
@gxt92 #1 我发现这个库生成 v7 的 uuid 并不是严格顺序的, 不知道啥情况
niubiman
49 天前
@asd999cxcx nanoid 比如用 ulid, 能短小精悍的同时保证有序, 减少数据库索引碎片
niubiman
49 天前
@niubiman 不如

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://yangjunhui.monster/t/1126358

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX