redis.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package dao
  2. import (
  3. "context"
  4. "go-common/library/cache/redis"
  5. "go-common/library/log"
  6. )
  7. // RedisIncr incr a key
  8. func (d *Dao) RedisIncr(ctx context.Context, key string) (num int64, err error) {
  9. num = 0
  10. conn := d.redis.Get(ctx)
  11. defer conn.Close()
  12. err = conn.Send("INCR", key)
  13. if err != nil {
  14. log.Error("[XCaptcha][Redis][error] conn.Send error(%v)", err)
  15. return
  16. }
  17. err = conn.Send("EXPIRE", key, 3)
  18. if err != nil {
  19. log.Error("[XCaptcha][Redis][error] conn.Send error(%v)", err)
  20. return
  21. }
  22. err = conn.Flush()
  23. if err != nil {
  24. log.Error("[XCaptcha][Redis][error] conn.Flush error(%v)", err)
  25. return
  26. }
  27. if num, err = redis.Int64(conn.Receive()); err != nil {
  28. log.Error("[XCaptcha][Redis][error] INCR conn.Receive error(%v)", key, err)
  29. return
  30. }
  31. if _, err = conn.Receive(); err != nil {
  32. log.Error("[XCaptcha][Redis][error] EXPIRE conn.Receive error(%v)", key, err)
  33. return
  34. }
  35. return
  36. }
  37. // RedisGet get a string
  38. func (d *Dao) RedisGet(ctx context.Context, key string) (value int64, err error) {
  39. value = 0
  40. conn := d.redis.Get(ctx)
  41. defer conn.Close()
  42. if value, err = redis.Int64(conn.Do("GET", key)); err != nil {
  43. log.Error("[XCaptcha][Redis][error] GET conn.do error(%v)", key, err)
  44. return
  45. }
  46. return
  47. }
  48. // RedisSet Set a string and expire
  49. func (d *Dao) RedisSet(ctx context.Context, key string, value int64, timeout int64) (err error) {
  50. conn := d.redis.Get(ctx)
  51. defer conn.Close()
  52. if _, err = conn.Do("SET", key, value, "EX", timeout); err != nil {
  53. log.Error("[XCaptcha][Redis][error] SET conn.do error(%v)", key, err)
  54. return
  55. }
  56. return
  57. }
  58. // RedisDel delete a key
  59. func (d *Dao) RedisDel(ctx context.Context, key string) (err error) {
  60. conn := d.redis.Get(ctx)
  61. defer conn.Close()
  62. if _, err = conn.Do("DEL", key); err != nil {
  63. log.Error("[XCaptcha][Redis][error] Delete conn.do error(%v)", key, err)
  64. return
  65. }
  66. return
  67. }