go语言雪花算法获取100000以内的数字
时间: 2023-07-16 18:17:36 浏览: 204
多语言新雪花算法(SnowFlake IdGenerator)-算法实现资源
下面是 Go 语言实现雪花算法获取100000以内的数字的示例代码:
```go
package main
import (
"fmt"
"math/rand"
"time"
)
const (
workerIDBits = 5
datacenterIDBits = 5
maxWorkerID = -1 ^ (-1 << workerIDBits)
maxDatacenterID = -1 ^ (-1 << datacenterIDBits)
sequenceBits = 12
workerIDShift = sequenceBits
datacenterIDShift = sequenceBits + workerIDBits
timestampLeftShift = sequenceBits + workerIDBits + datacenterIDBits
sequenceMask = -1 ^ (-1 << sequenceBits)
)
type snowflake struct {
lastTimestamp int64
sequence int64
workerID int64
datacenterID int64
}
func newSnowflake(workerID, datacenterID int64) *snowflake {
if workerID < 0 || workerID > maxWorkerID {
panic(fmt.Sprintf("Worker ID out of range: %d", workerID))
}
if datacenterID < 0 || datacenterID > maxDatacenterID {
panic(fmt.Sprintf("Datacenter ID out of range: %d", datacenterID))
}
return &snowflake{
workerID: workerID,
datacenterID: datacenterID,
}
}
func (sf *snowflake) nextID() int64 {
timestamp := time.Now().UnixNano() / 1000000
if timestamp < sf.lastTimestamp {
panic(fmt.Sprintf("Invalid timestamp: %v - precedes %v", timestamp, sf.lastTimestamp))
}
if timestamp == sf.lastTimestamp {
sf.sequence = (sf.sequence + 1) & sequenceMask
if sf.sequence == 0 {
timestamp = sf.waitNextMillis(timestamp)
}
} else {
sf.sequence = rand.Int63() & sequenceMask
}
sf.lastTimestamp = timestamp
return (timestamp << timestampLeftShift) |
(sf.datacenterID << datacenterIDShift) |
(sf.workerID << workerIDShift) |
sf.sequence
}
func (sf *snowflake) waitNextMillis(currentTimestamp int64) int64 {
for currentTimestamp == sf.lastTimestamp {
currentTimestamp = time.Now().UnixNano() / 1000000
}
return currentTimestamp
}
func main() {
sf := newSnowflake(1, 1)
for i := 0; i < 100000; i++ {
fmt.Println(sf.nextID())
}
}
```
在运行该程序时,会输出100000个雪花算法生成的 ID。
阅读全文