cleareids.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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() {
  34. defer wg.Done()
  35. clearPNCBKey(pncb, nowtime)
  36. }()
  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. 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. redis.Put(REDISKEYS, k, *ma.Arr, 0)
  88. }
  89. }
  90. }
  91. pKey.Lock.Unlock()
  92. return delkey
  93. }
  94. func deleteSliceId(a []string, id string) *[]string {
  95. ret := make([]string, 0, len(a))
  96. for _, val := range a {
  97. if val != id {
  98. ret = append(ret, val)
  99. }
  100. }
  101. return &ret
  102. }