uniqid.go 583 B

1234567891011121314151617181920212223242526272829303132333435
  1. package random
  2. import (
  3. "math"
  4. "math/rand"
  5. "time"
  6. )
  7. var (
  8. rnd *rand.Rand
  9. ch chan int64
  10. )
  11. func init() {
  12. rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  13. ch = make(chan int64, 1000)
  14. go randomBase(ch)
  15. }
  16. func randomBase(c chan int64) {
  17. for {
  18. c <- rnd.Int63()
  19. }
  20. }
  21. //Uniqid 随机数,length是需要返回的长度,只支持10~19位
  22. func Uniqid(length int) int64 {
  23. if length < 10 || length > 19 {
  24. return 0
  25. }
  26. prefix := (time.Now().UnixNano() / 100000000) & 0x3fffffff
  27. cut := int64(math.Pow10(length - 9))
  28. suffix := <-ch % cut
  29. return prefix*cut + suffix
  30. }