cleareids.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. // cleareids
  2. package main
  3. import (
  4. "encoding/json"
  5. "log"
  6. "qfw/util"
  7. "qfw/util/redis"
  8. "sync"
  9. "time"
  10. "github.com/robfig/cron"
  11. )
  12. var (
  13. c *cron.Cron
  14. projectcycle int64
  15. )
  16. func clearedis() {
  17. if credis, ok := Sysconfig["clearedis"].(map[string]interface{}); ok {
  18. clearcron := util.ObjToString(credis["clearcron"])
  19. projectcycle = util.Int64All(credis["projectcycle"])
  20. log.Println(credis)
  21. if credis["open"].(bool) {
  22. c = cron.New()
  23. c.AddFunc(clearcron, clearPKey)
  24. c.Start()
  25. }
  26. }
  27. }
  28. func clearPKey() {
  29. log.Println("开始清理")
  30. nowtime := time.Now().Unix()
  31. wg := sync.WaitGroup{}
  32. for _, pncb := range []*KeyMap{PNKey, PCKey, PBKey} {
  33. wg.Add(1)
  34. go func() {
  35. defer wg.Done()
  36. clearPNCBKey(pncb, nowtime)
  37. }()
  38. }
  39. wg.Wait()
  40. log.Println("清理结束")
  41. }
  42. func clearPNCBKey(pncb *KeyMap, nowtime int64) {
  43. delkey := clearIdsKeys(pncb, nowtime)
  44. pncb.Lock.Lock()
  45. for _, k := range delkey {
  46. delete(pncb.Map, k)
  47. }
  48. pncb.Lock.Unlock()
  49. }
  50. func clearIdsKeys(pKey *KeyMap, nowtime int64) []string {
  51. defer util.Catch()
  52. delkey := []string{}
  53. for k, ma := range pKey.Map {
  54. ids := ma.Arr
  55. delids := []interface{}{}
  56. res := redis.Mget(REDISIDS, *ids)
  57. for _, b1 := range res {
  58. if b1 != nil {
  59. var info ProjectInfo
  60. err := json.Unmarshal(b1.([]byte), &info)
  61. if err != nil {
  62. log.Println(err)
  63. continue
  64. }
  65. publistime := info.Publistime[len(info.Publistime)-1]
  66. if projectcycle < (nowtime-publistime)/86400 { //项目周期超时
  67. delids = append(delids, info.Id)
  68. }
  69. }
  70. }
  71. if len(delids) < 1 {
  72. continue
  73. }
  74. //删除redis相关信息
  75. b := redis.Del(REDISIDS, delids...)
  76. if b {
  77. for _, id := range delids {
  78. ids = deleteSliceId(*ids, id.(string))
  79. }
  80. log.Println(ids, *ma.Arr)
  81. ma.Arr = ids
  82. if len(*ma.Arr) < 1 {
  83. redis.Del(REDISKEYS, k)
  84. delkey = append(delkey, k)
  85. } else {
  86. //更新REDISKEYS
  87. l := redis.Get(REDISKEYS, k)
  88. log.Println(l, k, *ma.Arr)
  89. redis.Put(REDISKEYS, k, *ma.Arr, 0)
  90. }
  91. }
  92. }
  93. return delkey
  94. }
  95. func deleteSliceId(a []string, id string) *[]string {
  96. ret := make([]string, 0, len(a))
  97. for _, val := range a {
  98. if val != id {
  99. ret = append(ret, val)
  100. }
  101. }
  102. return &ret
  103. }