我们在工作中常常需要在分布式的服务器上,生成全服唯一的ID,同时还需要按时间有序;
之前在一个项目中拿 到一个这样的ID生成器,代码如下:
```go
// IDFetcher 获取唯一的TempID号
type IDFetcher struct {
baseID uint64
startID uint64
seed uint64
}
func newIDFetcher(srvID uint64) *IDFetcher {
return &IDFetcher{
baseID: srvID,
startID: uint64(time.Now().Unix()),
seed: 0,
}
}
func (srv *IDFetcher) FetchTempID() uint64 {
seed := srv.incSeed()
id := srv.baseID<<44 | srv.startID<<32 | seed
return id
}
func (srv *IDFetcher) incSeed() uint64 {
var n, v uint64
for {
v = atomic.LoadUint64(&srv.seed)
n = v + 1
if n > 0xFFFFFFFF {
n = 0
}
if atomic.CompareAndSwapUint64(&srv.seed, v, n) {
break
}
}
return n
}
```
然后发现一个问题,就是并发获取ID的时候,必然会有人触发for循环的逻辑导致多次获取ID;
于是我就想优化一下,就有了下面的代码:
```go
// IDGenerater 获取唯一的ID号
type IDGenerater struct {
baseID uint64
seed uint64
}
func NewIDGenerater(srvID uint64) *IDGenerater {
result := new(IDGenerater)
result.baseID = srvID
result.seed = uint64(time.Now().Unix()) << 16
return result
}
func (srv *IDGenerater) GenerateID() uint64 {
seed := atomic.AddUint64(&srv.seed, 1)
high := seed << 16 >> 16
tmptime := seed >> 16
for n := int64(tmptime - uint64(time.Now().Unix())); n > 0; n = int64(tmptime - uint64(time.Now().Unix())) {
time.Sleep(time.Duration(n-1)*time.Second + time.Millisecond*100)
}
result := srv.baseID<<48 | high
return result
}
```
今天拿出来和大家分享一下。欢迎大家一起交流!你们的ID生成器是怎么写的呢?