art_redis.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/cache/redis"
  6. "go-common/library/log"
  7. )
  8. func sortedKey(categoryID int64, field int) string {
  9. return fmt.Sprintf("art_sort_%d_%d", categoryID, field)
  10. }
  11. // ExpireSortCache expire sort cache
  12. func (d *Dao) ExpireSortCache(c context.Context, categoryID int64, field int) (ok bool, err error) {
  13. key := sortedKey(categoryID, field)
  14. conn := d.artRedis.Get(c)
  15. defer conn.Close()
  16. var ttl int64
  17. if ttl, err = redis.Int64(conn.Do("TTL", key)); err != nil {
  18. PromError("redis:排序缓存ttl")
  19. log.Error("conn.Do(TTL, %s) error(%+v)", key, err)
  20. }
  21. if ttl > (d.redisSortTTL - d.redisSortExpire) {
  22. ok = true
  23. }
  24. return
  25. }
  26. // AddSortCaches add sort articles cache
  27. func (d *Dao) AddSortCaches(c context.Context, categoryID int64, field int, arts [][2]int64, maxLength int64) (err error) {
  28. var (
  29. id, score int64
  30. key = sortedKey(categoryID, field)
  31. conn = d.artRedis.Get(c)
  32. count int
  33. )
  34. defer conn.Close()
  35. if len(arts) == 0 {
  36. return
  37. }
  38. if err = conn.Send("DEL", key); err != nil {
  39. PromError("redis:删除排序缓存")
  40. log.Error("conn.Send(DEL, %s) error(%+v)", key, err)
  41. return
  42. }
  43. count++
  44. for _, art := range arts {
  45. id = art[0]
  46. score = art[1]
  47. if err = conn.Send("ZADD", key, "CH", score, id); err != nil {
  48. PromError("redis:增加排序缓存")
  49. log.Error("conn.Send(ZADD, %s, %d, %v) error(%+v)", key, score, id, err)
  50. return
  51. }
  52. count++
  53. }
  54. if err = conn.Send("EXPIRE", key, d.redisSortTTL); err != nil {
  55. PromError("redis:排序缓存设定过期")
  56. log.Error("conn.Send(EXPIRE, %s, %d) error(%+v)", key, d.redisSortTTL, err)
  57. return
  58. }
  59. count++
  60. if err = conn.Flush(); err != nil {
  61. PromError("redis:增加排序缓存flush")
  62. log.Error("conn.Flush error(%+v)", err)
  63. return
  64. }
  65. for i := 0; i < count; i++ {
  66. if _, err = conn.Receive(); err != nil {
  67. PromError("redis:增加排序缓存receive")
  68. log.Error("conn.Receive error(%+v)", err)
  69. return
  70. }
  71. }
  72. return
  73. }