An Lock Free ID Generator for Golang implementation View on GitHub.node
Snowflake is a network service for generating unique ID numbers at high scale with some simple guarantees.git
The ID generated by the snowflake algorithm is not guaranteed to be unique. For example, when two different requests enter the same machine at the same time, and the sequence generated by the node is the same, the generated ID will be duplicated.github
So if you want use the snowflake algorithm to generate unique ID, You must ensure: The sequence-number generated in the same millisecond of the same node is unique.shell
Based on this, we created this package and integrated multiple sequence-number providers into it.ide
Each provider only needs to ensure that the serial number generated in the same millisecond is different. You can get a unique ID.
$ go get github.com/godruoyi/go-snowflake
package main import ( "fmt" "github.com/godruoyi/go-snowflake" ) func main() { id := snowflake.ID() fmt.Println(id) // 1537200202186752 }
package main import ( "fmt" "github.com/godruoyi/go-snowflake" ) func main() { snowflake.SetMachineID(1) // Or set private ip to machineid, testing... // snowflake.SetMachineID(snowflake.PrivateIPToMachineID()) id := snowflake.ID() fmt.Println(id) }
package main import ( "fmt" "time" "github.com/godruoyi/go-snowflake" ) func main() { snowflake.SetStartTime(time.Date(2014, 9, 1, 0, 0, 0, 0, time.UTC)) id := snowflake.ID() fmt.Println(id) }
package main import ( "fmt" "time" "github.com/godruoyi/go-snowflake" ) func main() { id := snowflake.ID() sid := snowflake.ParseID(id) fmt.Println(sid.ID) // 132271570944000000 fmt.Println(sid.MachineID) // 0 fmt.Println(sid.Sequence) // 0 fmt.Println(sid.Timestamp) // 31536000000 fmt.Println(sid.GenerateTime()) // 2009-11-10 23:00:00 +0000 UTC }
⚠️⚠️ All SetXXX method is thread-unsafe, recommended you call him in the main function.
package main import ( "fmt" "time" "net/http" "github.com/godruoyi/go-snowflake" ) func main() { snowflake.SetMachineID(1) // change to your machineID snowflake.SetStartTime(time.Date(2014, 9, 1, 0, 0, 0, 0, time.UTC)) http.HandleFunc("/order", submitOrder) http.ListenAndServe(":8090", nil) } func submitOrder(w http.ResponseWriter, req *http.Request) { orderId := snowflake.ID() // save order }
Custom sequence resolver. you can customize the sequence-number resolver by following way:ui
package main import ( "fmt" "time" "github.com/godruoyi/go-snowflake" ) func yourSequenceNumber(ms int64) (uint16, error) { } // usage snowflake.SetSequenceResolver(yourSequenceNumber) snowflake.ID()