Class UuidV7Generator

java.lang.Object
cloud.opencode.base.id.uuid.UuidV7Generator
All Implemented Interfaces:
IdGenerator<UUID>

public final class UuidV7Generator extends Object implements IdGenerator<UUID>
UUID v7 Generator UUID v7生成器

Generates time-ordered UUIDs based on RFC 9562 version 7. The first 48 bits contain Unix timestamp in milliseconds, making these UUIDs naturally sortable and database-friendly.

基于RFC 9562版本7生成时间有序的UUID。前48位包含Unix毫秒时间戳, 使这些UUID天然可排序且对数据库友好。

UUID v7 Structure | UUID v7结构:

0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                         unix_ts_ms (48 bits)                 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          unix_ts_ms           |  ver  |  rand_a (12 bits)    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|var|                    rand_b (62 bits)                      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                         rand_b                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Features | 主要功能:

  • Time-ordered for database efficiency - 时间有序,数据库高效
  • Monotonic within same millisecond - 同毫秒内单调递增
  • Lexicographically sortable - 字典序可排序

Usage Examples | 使用示例:

UuidV7Generator gen = UuidV7Generator.create();
UUID uuid = gen.generate();

// Extract timestamp
long timestamp = UuidV7Generator.extractTimestamp(uuid);

// Check if v7
boolean isV7 = UuidV7Generator.isV7(uuid);

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
Since:
JDK 25, opencode-base-id V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • create

      public static UuidV7Generator create()
      Creates a UUID v7 generator 创建UUID v7生成器
      Returns:
      generator | 生成器
    • generate

      public UUID generate()
      Description copied from interface: IdGenerator
      Generates the next ID 生成下一个ID
      Specified by:
      generate in interface IdGenerator<UUID>
      Returns:
      generated ID | 生成的ID
    • generateStr

      public String generateStr()
      Generates a UUID as string 生成UUID字符串
      Returns:
      UUID string | UUID字符串
    • extractTimestamp

      public static long extractTimestamp(UUID uuid)
      Extracts the timestamp from a UUID v7 从UUID v7提取时间戳
      Parameters:
      uuid - the UUID | UUID
      Returns:
      timestamp in milliseconds | 时间戳(毫秒)
    • isV7

      public static boolean isV7(UUID uuid)
      Checks if a UUID is version 7 检查UUID是否为版本7
      Parameters:
      uuid - the UUID | UUID
      Returns:
      true if v7 | 如果是v7返回true
    • getType

      public String getType()
      Description copied from interface: IdGenerator
      Gets the generator type name 获取生成器类型名称
      Specified by:
      getType in interface IdGenerator<UUID>
      Returns:
      type name | 类型名称