redis.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package show
  2. import (
  3. "context"
  4. "go-common/library/log"
  5. "go-common/library/cache/redis"
  6. )
  7. const (
  8. _prefix = "s_"
  9. )
  10. func keyRcmmd(mid string) string {
  11. return _prefix + mid
  12. }
  13. func keyCnt(mid string) string {
  14. return _prefix + mid + "_c"
  15. }
  16. // ExistRcmmndCache check recommend cache exists.
  17. func (d *Dao) ExistRcmmndCache(c context.Context, mid string) (exist bool, err error) {
  18. conn := d.rcmmndRds.Get(c)
  19. defer conn.Close()
  20. key := keyCnt(mid)
  21. exist, err = redis.Bool(conn.Do("EXISTS", key))
  22. if err != nil {
  23. log.Error("conn.Do(EXISTS, %s) error(%v)", key, err)
  24. }
  25. return
  26. }
  27. // AddRcmmndCache add recommend cache.
  28. func (d *Dao) AddRcmmndCache(c context.Context, mid string, aids ...int64) (err error) {
  29. conn := d.rcmmndRds.Get(c)
  30. defer conn.Close()
  31. key := keyRcmmd(mid)
  32. cntk := keyCnt(mid)
  33. args := redis.Args{}.Add(key).AddFlat(aids)
  34. conn.Send("RPUSH", args...)
  35. conn.Send("EXPIRE", key, d.rcmmndExp)
  36. conn.Send("INCRBY", cntk, len(aids))
  37. conn.Send("EXPIRE", cntk, d.rcmmndExp)
  38. if err = conn.Flush(); err != nil {
  39. log.Error("conn.Flush err(%v)", err)
  40. return
  41. }
  42. if _, err = conn.Receive(); err != nil {
  43. log.Error("conn.Receive() error(%v)", err)
  44. return
  45. }
  46. if _, err = conn.Receive(); err != nil {
  47. log.Error("conn.Receive() error(%v)", err)
  48. return
  49. }
  50. if _, err = conn.Receive(); err != nil {
  51. log.Error("conn.Receive() error(%v)", err)
  52. return
  53. }
  54. if _, err = conn.Receive(); err != nil {
  55. log.Error("conn.Receive() error(%v)", err)
  56. }
  57. return
  58. }
  59. // PopRcmmndCache pop recommend cache.
  60. func (d *Dao) PopRcmmndCache(c context.Context, mid string, cnt int) (aids []int64, err error) {
  61. conn := d.rcmmndRds.Get(c)
  62. defer conn.Close()
  63. key := keyRcmmd(mid)
  64. for i := 0; i < cnt; i++ {
  65. conn.Send("LPOP", key)
  66. }
  67. if err = conn.Flush(); err != nil {
  68. log.Error("conn.Flush error(%v)", err)
  69. return
  70. }
  71. var aid int64
  72. for i := 0; i < cnt; i++ {
  73. aid, err = redis.Int64(conn.Receive())
  74. if err != nil {
  75. if err == redis.ErrNil {
  76. err = nil
  77. continue
  78. } else {
  79. log.Error("conn.Do(ZREVRANGE, %v)", err)
  80. }
  81. return
  82. }
  83. aids = append(aids, aid)
  84. }
  85. return
  86. }