The following is a sample code for using Go to implement the snowflake algorithm to generate a 64-bit ID:
package main import ( "fmt" "sync" "time" ) const ( // Start timestamp (2020-01-01) twepoch = 1577836800000 workerIDBits = 5 datacenterIDBits = 5 sequenceBits = 12 maxWorkerID = -1 ^ (-1 << workerIDBits) maxDatacenterID = -1 ^ (-1 << datacenterIDBits) maxSequence = -1 ^ (-1 << sequenceBits) workerIDShift = sequenceBits datacenterIDShift = sequenceBits + workerIDBits timestampLeftShift = sequenceBits + workerIDBits + datacenterIDBits ) type Snowflake struct { mu lastTimestamp int64 workerID int64 datacenterID int64 sequence int64 } func NewSnowflake(workerID, datacenterID int64) (*Snowflake, error) { if workerID < 0 || workerID > maxWorkerID { return nil, ("worker ID must be between 0 and %d", maxWorkerID) } if datacenterID < 0 || datacenterID > maxDatacenterID { return nil, ("datacenter ID must be between 0 and %d", maxDatacenterID) } return &Snowflake{ workerID: workerID, datacenterID: datacenterID, lastTimestamp: -1, sequence: 0, }, nil } func (s *Snowflake) NextID() int64 { () defer () timestamp := ().UnixNano() / 1e6 if timestamp < { return 0 } if == timestamp { = ( + 1) & maxSequence if == 0 { for timestamp <= { timestamp = ().UnixNano() / 1e6 } } } else { = 0 } = timestamp return ((timestamp - twepoch) << timestampLeftShift) | ( << datacenterIDShift) | ( << workerIDShift) | }
You can call it using the following method:
func main() { sf, err := NewSnowflake(1, 1) if err!= nil { panic(err) } id := () (id) }
This implementation creates a structure of Snowflake algorithm, which ensures concurrency security through mutex locks. It generates a unique 64-bit ID based on the current timestamp, worker node ID, data center ID, and serial number. The generated ID is an incremental number, temporal sequential, and uniqueness can be guaranteed in a distributed system.
This is the article about the example code of golang snowflake algorithm implementing 64-bit ID. For more related golang 64-bit ID content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!