You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

reghelper.go 5.3 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package regworkerid
  2. import (
  3. "fmt"
  4. "github.com/go-redis/redis"
  5. "strconv"
  6. "sync"
  7. "time"
  8. )
  9. var Client *redis.Client
  10. var _usingWorkerId int = -1
  11. var _maxWorkerId int = 0
  12. var _loopCount int = 0
  13. var _liftIndex int = -1
  14. var _workerIdLock sync.Mutex
  15. const CurrentWidIndexKey string = "IdGen:WorkerId:Index"
  16. const WidKeyPrefix string = "IdGen:WorkerId:Value:"
  17. const WorkerIdFlag = "Y" // WorkerId 存储标记
  18. const WorkerIdLifeTimeSeconds = 15 // WorkerIdFlag 有效期(单位秒,最好是3的倍数)
  19. const Log = false
  20. func UnRegisterWorkerId() {
  21. if _usingWorkerId < 0 {
  22. return
  23. }
  24. _workerIdLock.Lock()
  25. Client.Del(WidKeyPrefix + strconv.Itoa(_usingWorkerId))
  26. _usingWorkerId = -1
  27. _liftIndex = -1
  28. _workerIdLock.Unlock()
  29. }
  30. func RegisterWorkerId(ip string, port int, password string, maxWorkerId int) int {
  31. // maxWorkerId不能小于0
  32. if maxWorkerId < 0 {
  33. return -1
  34. }
  35. // 如果当前已注册过 WorkerId,则先注销,并终止先前的自动续期线程
  36. if _usingWorkerId > -1 {
  37. UnRegisterWorkerId()
  38. }
  39. _maxWorkerId = maxWorkerId
  40. Client = redis.NewClient(&redis.Options{
  41. Addr: string(ip) + ":" + strconv.Itoa(port),
  42. PoolSize: 1000,
  43. ReadTimeout: time.Millisecond * time.Duration(100),
  44. WriteTimeout: time.Millisecond * time.Duration(100),
  45. IdleTimeout: time.Second * time.Duration(60),
  46. Password: password,
  47. })
  48. _, err := Client.Ping().Result()
  49. if err != nil {
  50. panic("init redis error")
  51. } else {
  52. if Log {
  53. fmt.Println("init redis ok")
  54. }
  55. }
  56. _loopCount = 0
  57. return getNextWorkerId()
  58. }
  59. func getNextWorkerId() int {
  60. // 获取当前 WorkerIdIndex
  61. // var currentId = int(Client.Incr(CurrentWidIndexKey).Val())
  62. r, err := Client.Incr(CurrentWidIndexKey).Result()
  63. if err != nil {
  64. return 0
  65. }
  66. currentId := int(r)
  67. if Log {
  68. fmt.Println("Begin currentId:" + strconv.Itoa(currentId))
  69. }
  70. // 如果 Index 大于最大值,则重置
  71. if currentId > _maxWorkerId {
  72. if canReset() {
  73. // 当前应用获得重置 WorkerIdIndex 的权限
  74. setWorkerIdIndex(-1)
  75. endReset() // 此步有可能不被执行?
  76. _loopCount++
  77. // 超过一定次数,直接终止操作
  78. if _loopCount > 10 {
  79. return -1
  80. }
  81. // if _loopCount > 2 {
  82. // 如果超过2个循环,则暂停1s
  83. time.Sleep(time.Duration(500*_loopCount) * time.Millisecond)
  84. //_loopCount = 0
  85. //}
  86. if Log {
  87. fmt.Println("canReset loop")
  88. }
  89. return getNextWorkerId()
  90. } else {
  91. // 如果有其它应用正在编辑,则本应用暂停1s后,再继续
  92. time.Sleep(time.Duration(1000) * time.Millisecond)
  93. if Log {
  94. fmt.Println("not canReset loop")
  95. }
  96. return getNextWorkerId()
  97. }
  98. }
  99. if Log {
  100. fmt.Println("currentId:" + strconv.Itoa(currentId))
  101. }
  102. if isAvailable(currentId) {
  103. if Log {
  104. fmt.Println("AA: isAvailable:" + strconv.Itoa(currentId))
  105. }
  106. // 最新获得的 WorkerIdIndex,在 redis 中是可用状态
  107. setWorkerIdFlag(currentId)
  108. _usingWorkerId = currentId
  109. // 获取到可用 WorkerId 后,启用新线程,每隔 1/3个 WorkerIdLifeTimeSeconds 时间,向服务器续期(延长一次 LifeTime)
  110. _liftIndex++
  111. go extendWorkerIdLifeTime(_liftIndex)
  112. return currentId
  113. } else {
  114. if Log {
  115. fmt.Println("BB: not isAvailable:" + strconv.Itoa(currentId))
  116. }
  117. // 最新获得的 WorkerIdIndex,在 redis 中是不可用状态,则继续下一个 WorkerIdIndex
  118. return getNextWorkerId()
  119. }
  120. }
  121. func extendWorkerIdLifeTime(lifeIndex int) {
  122. var index = lifeIndex
  123. for {
  124. time.Sleep(time.Duration(WorkerIdLifeTimeSeconds/3) * time.Millisecond)
  125. _workerIdLock.Lock()
  126. if index != _liftIndex {
  127. // 如果临时变量 index 不等于 全局变量 _liftIndex,表明全局状态被修改,当前线程可终止
  128. break
  129. }
  130. // 已经被注销,则终止(此步是上一步的二次验证)
  131. if _usingWorkerId < 0 {
  132. break
  133. }
  134. extendWorkerIdFlag(_usingWorkerId)
  135. _workerIdLock.Unlock()
  136. }
  137. }
  138. func get(key string) (string, bool) {
  139. r, err := Client.Get(key).Result()
  140. if err != nil {
  141. return "", false
  142. }
  143. return r, true
  144. }
  145. func set(key string, val string, expTime int32) {
  146. Client.Set(key, val, time.Duration(expTime)*time.Second)
  147. }
  148. func setWorkerIdIndex(val int) {
  149. Client.Set(CurrentWidIndexKey, val, 0)
  150. }
  151. func setWorkerIdFlag(index int) {
  152. Client.Set(WidKeyPrefix+strconv.Itoa(index), WorkerIdFlag, time.Duration(WorkerIdLifeTimeSeconds)*time.Second)
  153. }
  154. func extendWorkerIdFlag(index int) {
  155. Client.Expire(WidKeyPrefix+strconv.Itoa(index), time.Duration(WorkerIdLifeTimeSeconds)*time.Second)
  156. }
  157. func canReset() bool {
  158. r, err := Client.Incr(WidKeyPrefix + "Edit").Result()
  159. if err != nil {
  160. return false
  161. }
  162. if Log {
  163. fmt.Println("canReset:" + string(r))
  164. }
  165. return r != 1
  166. }
  167. func endReset() {
  168. // Client.Set(WidKeyPrefix+"Edit", 0, time.Duration(2)*time.Second)
  169. Client.Set(WidKeyPrefix+"Edit", 0, 0)
  170. }
  171. func getWorkerIdFlag(index int) (string, bool) {
  172. r, err := Client.Get(WidKeyPrefix + strconv.Itoa(index)).Result()
  173. if err != nil {
  174. return "", false
  175. }
  176. return r, true
  177. }
  178. func isAvailable(index int) bool {
  179. r, err := Client.Get(WidKeyPrefix + strconv.Itoa(index)).Result()
  180. if Log {
  181. fmt.Println("XX isAvailable:" + r)
  182. fmt.Println("YY isAvailable:" + err.Error())
  183. }
  184. if err != nil {
  185. if err.Error() == "redis: nil" {
  186. return true
  187. }
  188. return false
  189. }
  190. return r != WorkerIdFlag
  191. }

雪花算法中非常好用的数字ID生成器