util.go 880 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package model
  2. import (
  3. "app.yhyue.com/moapp/jybase/redis"
  4. "fmt"
  5. "math/rand"
  6. "strings"
  7. "time"
  8. )
  9. func GetRand(n int) int {
  10. randGen := rand.New(rand.NewSource(time.Now().UnixNano()))
  11. // 获取一个范围在 [0, ) 的随机整数
  12. return randGen.Intn(n)
  13. }
  14. // SaveHistory 保存历史记录
  15. func SaveHistory(matchKey string, userId string, redisKey string) bool {
  16. redisKey = fmt.Sprintf(redisKey, userId)
  17. history := redis.GetStr("other", redisKey)
  18. arrS := []string{}
  19. arrS = strings.Split(history, ",")
  20. //新增历史记录
  21. if history == "" {
  22. arrS = make([]string, 0)
  23. }
  24. for k, v := range arrS {
  25. if v == strings.TrimSpace(matchKey) {
  26. arrS = append(arrS[:k], arrS[k+1:]...)
  27. break
  28. }
  29. }
  30. arrS = append(arrS, strings.TrimSpace(matchKey))
  31. if len(arrS) > 10 {
  32. arrS = arrS[len(arrS)-10:]
  33. }
  34. return redis.Put("other", redisKey, strings.Join(arrS, ","), -1)
  35. }