redis.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "go-common/library/cache/redis"
  7. "go-common/library/log"
  8. "go-common/library/net/ip"
  9. )
  10. func reviewAuditNotifyLockKey(t time.Time) string {
  11. prefix := t.Format("2006-01-02-15")
  12. if t.Minute() < 30 {
  13. return fmt.Sprintf("review_notify_%s_00", prefix)
  14. }
  15. return fmt.Sprintf("review_notify_%s_30", prefix)
  16. }
  17. func (d *Dao) pingRedis(c context.Context) error {
  18. conn := d.redis.Get(c)
  19. defer conn.Close()
  20. _, err := conn.Do("SET", "ping", "pong")
  21. return err
  22. }
  23. // TryLockReviewNotify is
  24. func (d *Dao) TryLockReviewNotify(c context.Context, t time.Time) (bool, error) {
  25. key := reviewAuditNotifyLockKey(t)
  26. conn := d.redis.Get(c)
  27. defer conn.Close()
  28. locked, err := redis.Bool(conn.Do("SETNX", key, fmt.Sprintf("%s::%s", ip.InternalIP(), t)))
  29. if err != nil {
  30. return false, err
  31. }
  32. if !locked {
  33. return false, nil
  34. }
  35. if _, err := conn.Do("EXPIRE", key, 60*60); err != nil {
  36. log.Error("Failed to set expire on key: %s: %+v", key, err)
  37. // return
  38. }
  39. return locked, nil
  40. }