github.com/bwmarrin/snowflake
是一个相当轻量化的 snowflake 的 Go 实现。其文档对各位使用的定义如下图所示:
此库和标准的 snowflake
实现方式全完一致,使用也比较简单:
package main
import (
// 示例代码只导入提供核心功能的package,其他内置package自行导入,下同
"github.com/bwmarrin/snowflake"
)
func main() {
node, err := snowflake.NewNode(1)
if err != nil {
println(err.Error())
os.Exit(1)
}
for i := 0; i < 20; i++ {
id := node.Generate()
fmt.Printf("Int64 ID: %d\n", id)
fmt.Printf("String ID: %s\n", id)
fmt.Printf("Base2 ID: %s\n", id.Base2())
fmt.Printf("Base64 ID: %s\n", id.Base64())
fmt.Printf("ID Time : %d\n", id.Time())
fmt.Printf("ID Node : %d\n", id.Node())
fmt.Printf("ID Step : %d\n", id.Step())
fmt.Println("---------------------------------------------")
}
}
这个库因为是单文件,所以也方便定制,其源码本身就预留了一些可定制字段:
var (
// Epoch is set to the twitter snowflake epoch of Nov 04 2010 01:42:54 UTC in milliseconds
// You may customize this to set a different epoch for your application.
Epoch int64 = 1288834974657
// NodeBits holds the number of bits to use for Node
// Remember, you have a total 22 bits to share between Node/Step
NodeBits uint8 = 10
// StepBits holds the number of bits to use for Step
// Remember, you have a total 22 bits to share between Node/Step
StepBits uint8 = 12
)
Epoch
为起始时间,NodeBits
是实例id
的位长,StepBits
是自增id
的位长。
最后编辑: kuteng 文档更新时间: 2022-03-22 19:29 作者:kuteng