golang雪花算法實現(xiàn)64位的ID的示例代碼
以下是使用 Go 語言實現(xiàn)雪花算法生成 64 位 ID 的示例代碼:
package main
import (
"fmt"
"sync"
"time"
)
const (
// 起始時間戳(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 sync.Mutex
lastTimestamp int64
workerID int64
datacenterID int64
sequence int64
}
func NewSnowflake(workerID, datacenterID int64) (*Snowflake, error) {
if workerID < 0 || workerID > maxWorkerID {
return nil, fmt.Errorf("worker ID must be between 0 and %d", maxWorkerID)
}
if datacenterID < 0 || datacenterID > maxDatacenterID {
return nil, fmt.Errorf("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 {
s.mu.Lock()
defer s.mu.Unlock()
timestamp := time.Now().UnixNano() / 1e6
if timestamp < s.lastTimestamp {
return 0
}
if s.lastTimestamp == timestamp {
s.sequence = (s.sequence + 1) & maxSequence
if s.sequence == 0 {
for timestamp <= s.lastTimestamp {
timestamp = time.Now().UnixNano() / 1e6
}
}
} else {
s.sequence = 0
}
s.lastTimestamp = timestamp
return ((timestamp - twepoch) << timestampLeftShift) |
(s.datacenterID << datacenterIDShift) |
(s.workerID << workerIDShift) |
s.sequence
}
你可以使用以下方式調(diào)用:
func main() {
sf, err := NewSnowflake(1, 1)
if err!= nil {
panic(err)
}
id := sf.NextID()
fmt.Println(id)
}
這個實現(xiàn)創(chuàng)建了一個雪花算法的結(jié)構(gòu)體Snowflake,通過互斥鎖保證并發(fā)安全。它根據(jù)當(dāng)前時間戳、工作節(jié)點 ID、數(shù)據(jù)中心 ID 和序列號生成唯一的 64 位 ID。生成的 ID 是一個遞增的數(shù)字,具有時間順序性,并且在分布式系統(tǒng)中可以保證唯一性。
到此這篇關(guān)于golang雪花算法實現(xiàn)64位的ID的示例代碼的文章就介紹到這了,更多相關(guān)golang 64位的ID內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go語言中init函數(shù)與匿名函數(shù)使用淺析
這篇文章主要介紹了Go語言中init函數(shù)與匿名函數(shù)使用淺析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01
Go使用TimerController解決timer過多的問題
多路復(fù)用,實際上Go底層也是一種多路復(fù)用的思想去實現(xiàn)的timer,但是它是底層的timer,我們需要解決的問題就過多的timer問題!本文給大家介紹了Go使用TimerController解決timer過多的問題,需要的朋友可以參考下2024-12-12
linux下通過go語言獲得系統(tǒng)進程cpu使用情況的方法
這篇文章主要介紹了linux下通過go語言獲得系統(tǒng)進程cpu使用情況的方法,實例分析了Go語言使用linux的系統(tǒng)命令ps來分析cpu使用情況的技巧,需要的朋友可以參考下2015-03-03
go語言map與string的相互轉(zhuǎn)換的實現(xiàn)
這篇文章主要介紹了go語言map與string的相互轉(zhuǎn)換的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

