/
id_generator.go
112 lines (92 loc) · 1.57 KB
/
id_generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* @author: Jason
* Created: 19-5-3
*/
package utils
import (
"github.com/pkg/errors"
"math"
"container/list"
"sync"
)
var (
GenerateIdError = errors.New("Generate Id failed")
defaultIdGenerator = NewIdGenerator()
minId = uint64(1)
maxId = uint64(math.MaxUint64)
)
func GetId() uint64 {
return defaultIdGenerator.Get()
}
func GetAvailableId() uint64 {
return defaultIdGenerator.GetAvailableId()
}
func CollectId(id uint64) {
defaultIdGenerator.Put(id)
}
type IdGenerator struct {
mux sync.RWMutex
id uint64
cycleCount uint64
idList *list.List
}
func NewIdGenerator() *IdGenerator {
return &IdGenerator{
id: minId,
idList: list.New(),
}
}
func (idg *IdGenerator) Get() (id uint64) {
defer func() {
if recover() != nil {
panic(GenerateIdError)
}
}()
idg.mux.Lock()
id = idg.id
if id == maxId {
id = minId
idg.id = minId
idg.cycleCount++
} else {
idg.id++
}
idg.mux.Unlock()
return
}
func (idg *IdGenerator) GetAvailableId() (id uint64) {
defer func() {
if recover() != nil {
panic(GenerateIdError)
}
}()
idg.mux.Lock()
element := idg.idList.Front()
if element != nil {
id = element.Value.(uint64)
idg.idList.Remove(element)
idg.mux.Unlock()
return
}
id = idg.id
if id == maxId {
id = minId
idg.id = minId
idg.cycleCount++
} else {
idg.id++
}
idg.mux.Unlock()
return
}
func (idg *IdGenerator) CycleCount() uint64 {
idg.mux.RLock()
c := idg.cycleCount
idg.mux.RUnlock()
return c
}
func (idg *IdGenerator) Put(id uint64) {
idg.mux.Lock()
idg.idList.PushBack(id)
idg.mux.Unlock()
}