Go-API接口访问频率限制DEMO

末蓝、 2022-09-02 12:57 267阅读 0赞

代码片段如下:

  1. package utils
  2. import (
  3. "time"
  4. "base.domain.com/global"
  5. "github.com/go-redis/redis"
  6. )
  7. // Limiter 定义属性
  8. type Limiter struct {
  9. redisClient *redis.Client
  10. }
  11. // NewLimiter 创建新的limiter
  12. func NewLimiter() *Limiter {
  13. ipConfig := global.GetConfig("ip")
  14. redis := NewRedis(ipConfig.GetString("IP_FREQUENCE_LIMIT_REDIS"))
  15. return &Limiter{redisClient: redis.Client}
  16. }
  17. // Allow 通过redis的value判断第几次访问并返回是否允许访问
  18. func (l *Limiter) Allow(key string, visitNumber int64, visitPeriod time.Duration) bool {
  19. currentLength := l.redisClient.LLen(key).Val()
  20. if currentLength >= visitNumber {
  21. return false
  22. }
  23. if v := l.redisClient.Exists(key).Val(); v == 0 {
  24. pipe := l.redisClient.TxPipeline()
  25. pipe.RPush(key, key)
  26. pipe.Expire(key, visitPeriod)
  27. _, _ = pipe.Exec()
  28. } else {
  29. l.redisClient.RPushX(key, key)
  30. }
  31. return true
  32. }
  33. // DuplicateSubmit 限制表单重复提交
  34. func (l *Limiter) DuplicateSubmit(key string, visitNumber int64, visitPeriod time.Duration) bool {
  35. return l.redisClient.SetNX(key, visitNumber, visitPeriod).Val()
  36. }

有一定的缺陷哈,慎用。。。

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读