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.
 
 
 

38 lines
544 B

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