go 在gin中使用 接口限流工具redis_rate

news/2024/5/9 10:50:30

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)}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pgtn.cn/news/8.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

提交代码触发Jenkins流水线更新

提交哪个构建哪个 或者 某个指定分支提交才构建 jenkins自己的restful接口在权限认证上比较麻烦,所以我选择了Jenkins的插件generic-webhook-trigger 使用下来感觉没有选错 1. 安装jenkins插件generic-webhook-trigger 在系统配置中去安装插件。 2. 在Jenkinsfile…

java 生成grpc调用service

1. 安装protoc 这里以mac为例: brew install automake brew install libtool brew install protobuf检查 protoc --version2. 下载protoc-(java/go/kotlin)插件 到这里下载对应系统的exe文件 https://repo.maven.apache.org/maven2/io/grpc/protoc-gen-grpc-java…

从言行合一到知行合一

本篇记录突然的随想,偶尔停留 2021年只有两种人在写博客,一种是试图建立受众并从中获利的人,另一种是只想写出想法、而没有任何目标的人。 这两种人的行为都非常好。选择做你喜欢的事,坚持下去,它们最终都可以对他人…