redis.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package share
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "go-common/library/cache/redis"
  7. "go-common/library/log"
  8. xip "go-common/library/net/ip"
  9. )
  10. const (
  11. _prefixShare = "as"
  12. // the first shared every day
  13. _prefixFirst = "afs"
  14. )
  15. func redisKey(aid int64) string {
  16. return fmt.Sprintf("%s_%d", _prefixShare, aid)
  17. }
  18. func redisFKey(mid int64, date string) string {
  19. return fmt.Sprintf("%s_%s_%d", _prefixFirst, date, mid%10000)
  20. }
  21. // AddShare add a share with mid and ip to redis.
  22. func (d *Dao) AddShare(c context.Context, mid, aid int64, ip string) (ok bool, err error) {
  23. var (
  24. key = redisKey(aid)
  25. value = (mid << 32) | int64(xip.InetAtoN(ip))
  26. conn = d.rds.Get(c)
  27. )
  28. defer conn.Close()
  29. if err = conn.Send("SADD", key, value); err != nil {
  30. log.Error("conn.Send(SADD, %s, %d) error(%v)", key, value, err)
  31. return
  32. }
  33. if err = conn.Send("EXPIRE", key, d.expire); err != nil {
  34. log.Error("conn.Send(EXPIRE, %s, %d) error(%v)", key, value, err)
  35. return
  36. }
  37. if err = conn.Flush(); err != nil {
  38. log.Error("conn.Flush error(%v)", err)
  39. }
  40. if ok, err = redis.Bool(conn.Receive()); err != nil {
  41. log.Error("conn.Receive error(%v)", err)
  42. }
  43. if _, err = conn.Receive(); err != nil {
  44. log.Error("conn.Receive error(%v)", err)
  45. }
  46. return
  47. }
  48. // HadFirstShare if key not exist need set expire to one day.
  49. func (d *Dao) HadFirstShare(c context.Context, mid, aid int64, ip string) (had bool, err error) {
  50. var (
  51. date = time.Now().Format("0102")
  52. key = redisFKey(mid, date)
  53. addOk bool
  54. conn = d.rds.Get(c)
  55. )
  56. defer conn.Close()
  57. if addOk, err = redis.Bool(conn.Do("SADD", key, mid)); err != nil {
  58. log.Error("conn.Send(SADD, %s, %d) error(%v)", key, mid, err)
  59. return
  60. }
  61. if addOk {
  62. if _, err = conn.Do("EXPIRE", key, 24*60*60); err != nil {
  63. log.Error("conn.Send(EXPIRE, %s, 24*60*60) error(%v)", key, err)
  64. }
  65. }
  66. had = !addOk
  67. return
  68. }