redis.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/cache/redis"
  6. )
  7. const (
  8. // view
  9. _viewPrefix = "v_%d_%d_%s"
  10. )
  11. func viewKey(pid, aid int64, ip string) (key string) {
  12. if ip == "" {
  13. // let it pass if ip is empty.
  14. return
  15. }
  16. return fmt.Sprintf(_viewPrefix, pid, aid, ip)
  17. }
  18. // Intercept intercepts illegal views.
  19. func (d *Dao) Intercept(c context.Context, pid, aid int64, ip string) (ban bool) {
  20. var (
  21. err error
  22. exist bool
  23. key = viewKey(pid, aid, ip)
  24. conn = d.redis.Get(c)
  25. )
  26. defer conn.Close()
  27. if key == "" {
  28. return
  29. }
  30. if exist, err = redis.Bool(conn.Do("EXISTS", key)); err != nil {
  31. PromError("redis:EXISTS播放数", "conn.Do(EXISTS, %s) error(%v)", key, err)
  32. return
  33. }
  34. if exist {
  35. ban = true
  36. return
  37. }
  38. if err = conn.Send("SET", key, ""); err != nil {
  39. PromError("redis:SET播放数", "conn.Send(EXPIRE, %s) error(%v)", key, err)
  40. return
  41. }
  42. if err = conn.Send("EXPIRE", key, d.viewCacheTTL); err != nil {
  43. PromError("redis:EXPIRE播放数", "conn.Send(EXPIRE, %s) error(%v)", key, err)
  44. return
  45. }
  46. if err = conn.Flush(); err != nil {
  47. PromError("redis:播放数缓存Flush", "conn.Flush error(%v)", err)
  48. return
  49. }
  50. for i := 0; i < 2; i++ {
  51. if _, err = conn.Receive(); err != nil {
  52. PromError("redis:播放数缓存Receive", "conn.Receive() error(%v)", err)
  53. return
  54. }
  55. }
  56. return
  57. }