golang-yitisheng-server/server/common/snowflake/snowflake_test.go

38 lines
894 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package snowflake // 注意:这里必须是 package snowflake不能是 main
import (
"fmt"
"testing"
)
// 这是一个测试函数,用于验证功能
func TestGenerateID(t *testing.T) {
// 1. 初始化生成器
sf, err := NewSnowflake(1, 1)
if err != nil {
t.Fatalf("初始化失败: %v", err)
}
fmt.Println("=== 开始生成 ID ===")
// 2. 生成几个 ID
for i := 0; i < 5; i++ {
id, err := sf.NextId()
if err != nil {
t.Errorf("生成 ID 失败: %v", err)
} else {
fmt.Printf("生成 ID: %d\n", id)
}
}
// 3. 解析 ID 查看详情
id, _ := sf.NextId()
info := ParseId(id)
fmt.Printf("\nID 详情解析:\n")
fmt.Printf("ID: %d\n", info["id"])
fmt.Printf("时间: %s\n", info["time_str"])
fmt.Printf("数据中心: %d\n", info["datacenterId"])
fmt.Printf("工作机器: %d\n", info["workerId"])
fmt.Printf("序列号: %d\n", info["sequence"])
}