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

43 lines
747 B

  1. package client
  2. import (
  3. "strconv"
  4. "sync/atomic"
  5. "time"
  6. )
  7. var (
  8. // Global ID generator
  9. // Default is an autoincrement ID generator
  10. IdGen IdGenerator
  11. )
  12. func init() {
  13. IdGen = NewAutoIncId()
  14. }
  15. // ID generator interface. Users can implament this for
  16. // their own generator.
  17. type IdGenerator interface {
  18. Id() string
  19. }
  20. // AutoIncId
  21. type autoincId struct {
  22. value int64
  23. }
  24. func (ai *autoincId) Id() string {
  25. next := atomic.AddInt64(&ai.value, 1)
  26. return strconv.FormatInt(next, 10)
  27. }
  28. // NewAutoIncId returns an autoincrement ID generator
  29. func NewAutoIncId() IdGenerator {
  30. // we'll consider the nano fraction of a second at startup unique
  31. // and count up from there.
  32. return &autoincId{
  33. value: int64(time.Now().Nanosecond()) << 32,
  34. }
  35. }