random.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package public
  2. import (
  3. "bytes"
  4. cr "crypto/rand"
  5. "math/big"
  6. "math/rand"
  7. "qfw/util/redis"
  8. "service/config"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var VarLSCPool = &LSCPool{
  14. JobQueue: make(chan string, config.Sysconfig.JobNum),
  15. WorkerNum: config.Sysconfig.WorkerNum,
  16. Lock: &sync.Mutex{},
  17. Randoms: "",
  18. }
  19. type LSCPool struct {
  20. JobQueue chan string //待取的口令
  21. WorkerNum int //当前工作的协程数
  22. Lock *sync.Mutex //口令锁
  23. Randoms string //口令集合
  24. }
  25. func (this *LSCPool) GetJob() string {
  26. return <-this.JobQueue
  27. }
  28. var r *rand.Rand
  29. func init() {
  30. r = rand.New(rand.NewSource(time.Now().Unix()))
  31. for i := 0; i < VarLSCPool.WorkerNum/2; i++ {
  32. go func() {
  33. for {
  34. VarLSCPool.JobQueue <- VarLSCPool.GetRandom()
  35. }
  36. }()
  37. }
  38. }
  39. //获取随机字符串
  40. func (this *LSCPool) GetRandom() string {
  41. this.Lock.Lock()
  42. defer this.Lock.Unlock()
  43. //如果使用过了 重新获取
  44. for {
  45. LSC := this.SpecialChar(0) + this.LetterRandom(8)
  46. if strings.Contains(this.Randoms, LSC) {
  47. continue
  48. }
  49. this.Randoms += LSC + "|"
  50. ok, _ := redis.Exists("other", "DIS_"+LSC)
  51. if ok {
  52. continue
  53. }
  54. // log.Println("获取口令:", LSC)
  55. return LSC
  56. }
  57. return ""
  58. }
  59. //字母随机串
  60. func (this *LSCPool) LetterRandom(LL int) (LR string) {
  61. bytes := make([]byte, LL)
  62. for i := 0; i < LL; i++ {
  63. b := r.Intn(26) + 65
  64. bytes[i] = byte(b)
  65. }
  66. LR = string(bytes)
  67. return
  68. }
  69. //特殊字符随机串
  70. func (this *LSCPool) SpecialChar(LL int) (SC string) {
  71. var str = "$#"
  72. b := bytes.NewBufferString(str)
  73. length := b.Len()
  74. bigInt := big.NewInt(int64(length))
  75. for i := 0; i < LL; i++ {
  76. randomInt, _ := cr.Int(cr.Reader, bigInt)
  77. SC += string(str[randomInt.Int64()])
  78. }
  79. return
  80. }