UUIDv7 在 33 种语言中

主要观点:介绍了 UUIDv7 这一 128 位唯一标识符,它像 UUIDv4 等前辈一样,具有时间可排序(1 毫秒精度)的特点,是数据库(包括分布式数据库)中记录标识符的优秀选择。提供了 33 种语言的零依赖实现代码,并详细说明了 UUIDv7 的结构及各部分含义,最后提到了相关规范的发布时间及对其的期望。
关键信息

  • UUIDv7 结构:由 48 位时间戳(毫秒级 Unix 时间戳)、4 位版本号(7)、12 位随机数(rand_a)、2 位固定变体(10)、62 位随机数(rand_b)组成。
  • 33 种语言实现:包括 JavaScript、Python、SQL、Shell、Java、C#、C++、C、PHP、PowerShell、Go、Rust、Kotlin、Ruby、Lua、Dart、Swift、R、Pascal、Perl、Elixir、Clojure、Julia、Erlang、Zig、Crystal、Nim、Gleam、Tcl、V、Emacs Lisp、Vimscript、Nushell 等,各语言实现方式不同但原理相似。
  • 相关规范:RFC 9652 规定了 UUIDv7 的细节,RFC 4122 于 2005 年发布,UUIDv7 是对时间有序 UUID 的标准更新。
    重要细节
  • JavaScript 实现通过 crypto.getRandomValues()获取随机数,Date.now()获取当前时间戳来填充 UUID 数组。
  • Python 利用 os.urandom()获取随机数,time.time()获取当前时间戳。
  • SQL 在不同数据库(如 SQLite、PostgreSQL、SQL Server)中有不同的实现方式,通过相应函数获取时间戳和随机数并拼接。
  • Shell 脚本通过 /dev/urandom获取随机数,date获取当前时间戳。
  • Java 使用 SecureRandom.nextBytes()System.currentTimeMillis()
  • C#借助 RandomNumberGenerator.GetBytes()DateTimeOffset.UtcNow
  • C 语言通过 getentropy()获取随机数,timespec_get()获取时间戳。
  • PHP 利用 random_bytes()microtime()
  • PowerShell 使用 Random.GetBytes()DateTimeOffset.UtcNow
  • Go 以 rand.Read()获取随机数,time.Now()获取时间戳。
  • Rust 通过 getrandom::getrandom()SystemTime::now()
  • Kotlin 借助 SecureRandom.nextBytes()Instant.now()
  • Ruby 使用 SecureRandom.random_bytes()Time.now
  • Lua 生成随机表,通过 os.time()获取时间戳。
  • Dart 利用 Random.secure()DateTime.now()
  • Swift 扩展 UUID类型,通过 UInt8.random()获取随机数,Date().timeIntervalSince1970获取时间戳。
  • R 语言使用 sample()Sys.time()
  • Pascal 通过 Random()DateTimeToUnix()
  • Perl 利用 rand()Time::HiRes::time()
  • Elixir 借助 crypto.strong_rand_bytes()os.system_time()
  • Clojure 使用 SecureRandom.nextBytes()System.currentTimeMillis()
  • Julia 通过 rand()time()
  • Erlang 生成随机字节,通过 os:system_time()获取时间戳。
  • Zig 利用 std.crypto.random.bytes()std.time.milliTimestamp()
  • Crystal 初始化随机切片,通过 Time.utc获取时间戳。
  • Nim 通过 random.rand()times.epochTime()
  • Gleam 初始化随机位数组,通过 crypto.strong_rand_bytes()os.system_time()
  • Tcl 生成随机数组,通过 rand()clock milliseconds获取时间戳。
  • V 语言利用 rand.bytes()time.now()
  • Emacs Lisp 通过 randomcurrent-time获取随机数和时间戳。
  • Vimscript 通过 randlocaltime获取随机数和时间戳。
  • Nushell 生成随机字节,通过 date now获取时间戳。
阅读 23
0 条评论