go 在gin中使用 接口限流工具redis_rate
github.com/go-redis/redis_rate/v9@v9.1.2
配置一个Limiter
// 第一个参数和第二个参数分别是接口路径和用户标识,用以唯一确定用户。
// 第三个用户是限流参数,即频次限制
func NewRateLimiter(path string, useSubject bool, limit redis_rate.Limit) func(c *gin.Context) {return func(c *gin.Context) {key := pathif useSubject {key += ":" + c.GetString("sub")}ctx := context.Background()limiter := redis_rate.NewLimiter(redis_client.Client)res, err := limiter.Allow(ctx, key, limit)if err != nil {panic(exception.NewApiError(exception.RateLimitError, err.Error()))}log.Debug("allowed: ", res.Allowed, ", remaining: ", res.Remaining)if res.Allowed == 0 {panic(exception.PredefinedError(exception.RateLimitError))}}
}
使用,在路由处设置。
func Init(r *gin.Engine) {apiV1 := r.Group("/api/v1"){// 创建一个排行榜, 限流1s一次apiV1.POST("/rankings",middleware.NewRateLimiter("post/ranking", true, redis_rate.PerSecond(1)),v1.CreateRanking)}
}