prompt_redis.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/cache/redis"
  6. )
  7. const (
  8. _cacheShard = 10000
  9. _upPrompt = "rl_up_%d_%d" // key of upper prompt; hashes(fid-count)
  10. _buPrompt = "rl_bu_%d_%d_%d" // key of business type prompt;hashes(mid-count)
  11. )
  12. // key upPrompt : rl_up_mid_ts/period
  13. func (d *Dao) upPrompt(mid, ts int64) string {
  14. return fmt.Sprintf(_upPrompt, mid, ts/d.period)
  15. }
  16. // key _buPrompt : rl_bu_businesstype_mid/10000_ts
  17. func (d *Dao) buPrompt(btype int8, mid, ts int64) string {
  18. return fmt.Sprintf(_buPrompt, btype, mid/_cacheShard, ts/d.period)
  19. }
  20. // IncrPromptCount incr up prompt count and business type prompt count.
  21. func (d *Dao) IncrPromptCount(c context.Context, mid, fid, ts int64, btype int8) (ucount, bcount int64, err error) {
  22. conn := d.redis.Get(c)
  23. defer conn.Close()
  24. keyUp := d.upPrompt(mid, ts)
  25. keyBs := d.buPrompt(btype, mid, ts)
  26. conn.Send("HINCRBY", keyUp, fid, 1)
  27. conn.Send("EXPIRE", keyUp, d.period)
  28. conn.Send("HINCRBY", keyBs, mid, 1)
  29. conn.Send("EXPIRE", keyBs, d.period)
  30. err = conn.Flush()
  31. if err != nil {
  32. return
  33. }
  34. ucount, err = redis.Int64(conn.Receive())
  35. if err != nil {
  36. return
  37. }
  38. conn.Receive()
  39. bcount, err = redis.Int64(conn.Receive())
  40. if err != nil {
  41. return
  42. }
  43. conn.Receive()
  44. return
  45. }
  46. // ClosePrompt set prompt count to max config value.
  47. func (d *Dao) ClosePrompt(c context.Context, mid, fid, ts int64, btype int8) (err error) {
  48. conn := d.redis.Get(c)
  49. defer conn.Close()
  50. keyUp := d.upPrompt(mid, ts)
  51. keyBs := d.buPrompt(btype, mid, ts)
  52. conn.Send("HSET", keyUp, fid, d.ucount)
  53. conn.Send("HSET", keyBs, mid, d.bcount)
  54. return conn.Flush()
  55. }
  56. // UpCount get upper prompt count.
  57. func (d *Dao) UpCount(c context.Context, mid, fid, ts int64) (count int64, err error) {
  58. conn := d.redis.Get(c)
  59. count, err = redis.Int64(conn.Do("HGET", d.upPrompt(mid, ts), fid))
  60. conn.Close()
  61. return
  62. }
  63. // BCount get business type prompt count.
  64. func (d *Dao) BCount(c context.Context, mid, ts int64, btype int8) (count int64, err error) {
  65. conn := d.redis.Get(c)
  66. count, err = redis.Int64(conn.Do("HGET", d.buPrompt(btype, mid, ts), mid))
  67. conn.Close()
  68. return
  69. }