cleareids.go 2.2 KB

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