redis.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package dao
  2. import (
  3. "context"
  4. "strconv"
  5. "time"
  6. "go-common/library/cache/redis"
  7. "go-common/library/log"
  8. )
  9. const (
  10. _expire = 30 * 60 // 30 minutes
  11. _prefixCaptcha = "recovery:ca_"
  12. )
  13. // SetLinkMailCount set linkMail expire time.
  14. func (d *Dao) SetLinkMailCount(c context.Context, linkMail string) (state int64, err error) {
  15. conn := d.redis.Get(c)
  16. defer conn.Close()
  17. //用时间戳去减去时间 当天0点过期,第二天又可以发送10封邮件
  18. i, _ := redis.Int(conn.Do("incr", linkMail))
  19. conn.Do("expire", linkMail, getSubtime())
  20. if i >= 11 { //第10封邮件之后
  21. state = 10 //当天邮件发送到达最大次数
  22. return
  23. }
  24. return
  25. }
  26. func getSubtime() (subtime int64) {
  27. timeStr := time.Now().Format("2006-01-02")
  28. t, _ := time.Parse("2006-01-02", timeStr)
  29. t2 := t.AddDate(0, 0, 1).Unix()
  30. curr := time.Now().Unix() //当前时间
  31. subtime = t2 - curr
  32. return
  33. }
  34. // keyCaptcha
  35. func keyCaptcha(mid int64, linkMail string) string {
  36. return _prefixCaptcha + strconv.FormatInt(mid, 10) + "_" + linkMail
  37. }
  38. // SetCaptcha set linkMail expire time.
  39. func (d *Dao) SetCaptcha(c context.Context, code string, mid int64, linkMail string) (err error) {
  40. conn := d.redis.Get(c)
  41. defer conn.Close()
  42. key := keyCaptcha(mid, linkMail)
  43. //验证码30分钟内有效
  44. if _, err = conn.Do("SETEX", key, _expire, code); err != nil {
  45. log.Error("conn.Do(SETEX, %d, %v, %s) error(%v)", mid, _expire, code, err)
  46. }
  47. return
  48. }
  49. // GetEMailCode get captcha from redis
  50. func (d *Dao) GetEMailCode(c context.Context, mid int64, linkMail string) (code string, err error) {
  51. key := keyCaptcha(mid, linkMail)
  52. conn := d.redis.Get(c)
  53. defer conn.Close()
  54. code, err = redis.String(conn.Do("GET", key))
  55. if err != nil {
  56. if err == redis.ErrNil {
  57. err = nil
  58. return
  59. }
  60. log.Error("conn.Do(GET, %s, ), err (%v)", key, err)
  61. return
  62. }
  63. return
  64. }
  65. // DelEMailCode del captcha from redis 提交:校验验证之后就删除验证码(保证只能提交一次)
  66. func (d *Dao) DelEMailCode(c context.Context, mid int64, linkMail string) (err error) {
  67. key := keyCaptcha(mid, linkMail)
  68. conn := d.redis.Get(c)
  69. defer conn.Close()
  70. if _, err = conn.Do("DEL", key); err != nil {
  71. log.Error("conn.Do(DEL, %s, ), err (%v)", key, err)
  72. return
  73. }
  74. return
  75. }
  76. // PingRedis check connection success.
  77. func (d *Dao) PingRedis(c context.Context) (err error) {
  78. conn := d.redis.Get(c)
  79. defer conn.Close()
  80. _, err = conn.Do("GET", "PING")
  81. return
  82. }