Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Snowflake ID 生成器

Feature: snow

配置

[snow]
epoch = 0              # 自定义起始时间(毫秒时间戳),0 = 使用当前时间
worker_id = 1          # 机器 ID (0~31)
datacenter_id = 1      # 数据中心 ID (0~31)

API

SnowConfig

配置结构体,从 config.toml 读取。

字段类型默认值说明
epochi640起始时间戳(毫秒),0 表示当前时间
worker_idi641机器 ID (0~31)
datacenter_idi641数据中心 ID (0~31)

Snowflake

方法参数返回说明
from_configconfig: &SnowConfigSnowflake从配置创建实例
next_id-i64生成下一个唯一 ID(async)
next_id_str-String生成下一个唯一 ID(async,字符串)
next_id_prefixprefix: &strString生成带前缀的唯一 ID(async)

使用示例

#![allow(unused)]
fn main() {
// 通过 AppState 访问(已从 config 自动初始化)
let id = state.snow.next_id().await;
let id_str = state.snow.next_id_str().await;
let order_no = state.snow.next_id_prefix("ORD").await;
}

ID 结构

| 1 bit | 41 bits timestamp | 5 bits datacenter | 5 bits worker | 12 bits sequence |
  • 时间精度: 毫秒
  • 理论最大: ~69 年
  • 单机每毫秒: 4096 个 ID