The Snowflake ID Generator is a Go package that allows you to generate unique and distributed IDs based on a combination of timestamp, machine ID, and sequence number.
To use the Snowflake ID Generator in your Go project, you can simply install it using the go get
command:
go get -u github.com/naruepanart/snowflakeid
To use the Snowflake ID Generator in your Go application, follow these steps:
- Import the package:
import (
"fmt"
"github.com/naruepanart/snowflakeid"
)
- Create a Snowflake instance with a unique machine ID:
machineID := 1 // Set the machine ID according to the actual scenario
sf := snowflakeid.NewSnowflake(int64(machineID))
- Generate unique IDs using the
GenerateID
method:
for i := 0; i < 10; i++ {
id := sf.GenerateID()
fmt.Println(id)
}
Here's a complete example of using the Snowflake ID Generator in a Go application:
package main
import (
"fmt"
"github.com/naruepanart/snowflakeid"
)
func main() {
machineID := 1 // Set the machine ID according to the actual scenario
sf := snowflakeid.NewSnowflake(int64(machineID))
// Generate and print 10 unique IDs
for i := 0; i < 10; i++ {
id := sf.GenerateID()
fmt.Println(id)
}
}
Adjust the machine ID based on your deployment environment.
If you find any issues or have suggestions for improvements, feel free to open an issue or submit a pull request.