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.

SnowWorkerM2.go 1.1 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. * 版权属于:yitter(yitter@126.com)
  3. * 代码编辑:guoyahao
  4. * 代码修订:yitter
  5. * 开源地址:https://gitee.com/yitter/idgenerator
  6. */
  7. package idgen
  8. import (
  9. "fmt"
  10. "strconv"
  11. )
  12. type SnowWorkerM2 struct {
  13. *SnowWorkerM1
  14. }
  15. func NewSnowWorkerM2(options *IdGeneratorOptions) ISnowWorker {
  16. return &SnowWorkerM2{
  17. NewSnowWorkerM1(options).(*SnowWorkerM1),
  18. }
  19. }
  20. func (m2 SnowWorkerM2) NextId() int64 {
  21. m2.Lock()
  22. defer m2.Unlock()
  23. currentTimeTick := m2.GetCurrentTimeTick()
  24. if m2._LastTimeTick == currentTimeTick {
  25. m2._CurrentSeqNumber++
  26. if m2._CurrentSeqNumber > m2.MaxSeqNumber {
  27. m2._CurrentSeqNumber = m2.MinSeqNumber
  28. currentTimeTick = m2.GetNextTimeTick()
  29. }
  30. } else {
  31. m2._CurrentSeqNumber = m2.MinSeqNumber
  32. }
  33. if currentTimeTick < m2._LastTimeTick {
  34. fmt.Println("Time error for {0} milliseconds", strconv.FormatInt(m2._LastTimeTick-currentTimeTick, 10))
  35. }
  36. m2._LastTimeTick = currentTimeTick
  37. result := int64(currentTimeTick << m2._TimestampShift) + int64(m2.WorkerId<<m2.SeqBitLength) + int64(m2._CurrentSeqNumber)
  38. return result
  39. }

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