详解Golang雪花算法:生成唯一ID的最佳实践

发表时间: 2024-06-01 21:30

github地址

github.com/bwmarrin/snowflake


go get github.com/bwmarrin/snowflake

示例程序:

package mainimport (    "fmt"    "github.com/bwmarrin/snowflake")func main() {        // Create a new Node with a Node number of 1  	node, err := snowflake.NewNode(1)  	if err != nil {            fmt.Println(err)            return    }    // Generate a snowflake ID.    id := node.Generate()    // Print out the ID in a few different ways.    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())    // Print out the ID's timestamp    fmt.Printf("ID Time : %d\n", id.Time())    // Print out the ID's node number    fmt.Printf("ID Node : %d\n", id.Node())    // Print out the ID's sequence number    fmt.Printf("ID Step : %d\n", id.Step())    // Generate and print, all in one.    fmt.Printf("ID : %d\n", node.Generate().Int64())}
输出结果Int64 ID: 1297712694824013824String ID: 1297712694824013824Base2 ID: 1001000000010011001101101001000000011100000000001000000000000Base64 ID: MTI5NzcxMjY5NDgyNDAxMzgyNA==ID Time : 1598233791439ID Node : 1ID Step : 0ID : 1297712694828208128