cache.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package utils
  2. import (
  3. "gd_service/errors"
  4. "time"
  5. "gd_service/apis"
  6. "gd_service/common.in/cache"
  7. "gd_service/consts"
  8. "github.com/json-iterator/go"
  9. )
  10. func IsReuseTime(reuseTime int64, timestamp int64) bool {
  11. if timestamp == 0 {
  12. return false
  13. }
  14. reuseSencod := reuseTime * consts.DAYSECOND
  15. t := time.Unix(timestamp, 0)
  16. now := time.Now()
  17. // 60s短时复用
  18. if reuseTime == 0 {
  19. if now.Unix()-timestamp > consts.MINUTESECOND {
  20. return false
  21. }
  22. return true
  23. }
  24. start := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()).Unix()
  25. end := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
  26. if end-start >= reuseSencod {
  27. return false
  28. }
  29. return true
  30. }
  31. func GetDataByRedis(redisKey string, reuseTime int64, fn func(data string) (string, error)) (string, error) {
  32. res, err := cache.Redis.Get(redisKey)
  33. if err == nil && res != "" {
  34. rawData := apis.RawData{}
  35. _ = jsoniter.UnmarshalFromString(res, &rawData)
  36. if IsReuseTime(reuseTime, rawData.Timestamp) {
  37. return fn(rawData.Data)
  38. }
  39. }
  40. return "",errors.ServiceError
  41. }
  42. func StoreDataToRedis(redisKey, data string) {
  43. store := apis.RawData{
  44. Data: data,
  45. Timestamp: time.Now().Unix(),
  46. }
  47. str, _ := jsoniter.MarshalToString(store)
  48. _, _ = cache.Redis.SetEx(redisKey, consts.RedisDataExipred, str)
  49. return
  50. }