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.

DefaultIdGenerator.go 1.9 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
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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * 版权属于:yitter(yitter@126.com)
  3. * 代码编辑:guoyahao
  4. * 代码修订:yitter
  5. * 开源地址:https://gitee.com/yitter/idgenerator
  6. */
  7. package idgen
  8. import (
  9. "time"
  10. "yitidgen/contract"
  11. "yitidgen/core"
  12. )
  13. type DefaultIdGenerator struct {
  14. Options *contract.IdGeneratorOptions
  15. SnowWorker contract.ISnowWorker
  16. IdGeneratorException contract.IdGeneratorException
  17. }
  18. func NewDefaultIdGenerator(options *contract.IdGeneratorOptions) *DefaultIdGenerator {
  19. if options == nil {
  20. panic("dig.Options error.")
  21. }
  22. minTime := int64(631123200000) // time.Now().AddDate(-30, 0, 0).UnixNano() / 1e6
  23. if options.BaseTime < minTime || options.BaseTime > time.Now().UnixNano()/1e6 {
  24. panic("BaseTime error.")
  25. }
  26. if options.SeqBitLength+options.WorkerIdBitLength > 22 {
  27. panic("error:WorkerIdBitLength + SeqBitLength <= 22")
  28. }
  29. maxWorkerIdNumber := uint16(1<<options.WorkerIdBitLength) - 1
  30. if options.WorkerId > maxWorkerIdNumber {
  31. panic("WorkerId error. (range:[1, " + string(maxWorkerIdNumber) + "]")
  32. }
  33. if options.SeqBitLength < 2 || options.SeqBitLength > 21 {
  34. panic("SeqBitLength error. (range:[2, 21])")
  35. }
  36. maxSeqNumber := uint32(1<<options.SeqBitLength) - 1
  37. if options.MaxSeqNumber > maxSeqNumber {
  38. panic("MaxSeqNumber error. (range:[1, " + string(maxSeqNumber) + "]")
  39. }
  40. if options.MinSeqNumber > maxSeqNumber {
  41. panic("MinSeqNumber error. (range:[1, " + string(maxSeqNumber) + "]")
  42. }
  43. var snowWorker contract.ISnowWorker
  44. switch options.Method {
  45. case 1:
  46. snowWorker = core.NewSnowWorkerM1(options)
  47. case 2:
  48. snowWorker = core.NewSnowWorkerM2(options)
  49. default:
  50. snowWorker = core.NewSnowWorkerM1(options)
  51. }
  52. if options.Method == 1 {
  53. time.Sleep(time.Duration(500) * time.Microsecond)
  54. }
  55. return &DefaultIdGenerator{
  56. Options: options,
  57. SnowWorker: snowWorker,
  58. }
  59. }
  60. func (dig DefaultIdGenerator) NewLong() uint64 {
  61. return dig.SnowWorker.NextId()
  62. }

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