教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Go实现接口访问速率限制

Go实现接口访问速率限制

发布时间:2021-12-18   编辑:jiaochengji.com
教程集为您提供Go实现接口访问速率限制等资源,欢迎您收藏本站,我们将为您提供最新的Go实现接口访问速率限制资源

<span style="font-size:18px">接口的访问限制,10分钟内,接口访问限制100次</span>

<span style="font-size:18px">基于go语言进行编写,抽离出统一配置。</span>

<span style="font-size:18px">
</span>

<span style="font-size:18px"/>

<pre><code class="language-plain">func CheckRateLimit(ip, request, action string) bool { current := int(time.Now().Unix()) currentStr := strconv.Itoa(current) //limit 100次 //timeset 600秒 //限制600秒最多访问100次 limit, timeset := GetRateLimitConfig() allowanceStr, timestampStr := LoadAllowance(ip, request, action) allowance, _ := strconv.Atoi(allowanceStr) timestamp, _ := strconv.Atoi(timestampStr) allowance = int(current-timestamp) * limit / timeset if allowance > limit { allowance = limit } if allowance < 1 { SaveAllowance(ip, request, action, "0", currentStr) //返回true 代表速率超过,进行错误输出 return true } else { allowanceStr = strconv.Itoa(allowance - 1) SaveAllowance(ip, request, action, allowanceStr, currentStr) //返回false 代表速率未超过 return false } } func LoadAllowance(ip, request, action string) (allowance, timestamp string) { redisConfig := getRedisConfig() rs, err := cache.NewCache("redis", redisConfig) if err != nil { fmt.Println(err) return } res, _ := (redis.String(rs.Get(ip "_" request), err)) if len(res) == 0 { currentStr := string(time.Now().Unix()) defaultLimitInt, _ := GetRateLimitConfig() defaultLimitStr := strconv.Itoa(defaultLimitInt) allowance, timestamp = defaultLimitStr, currentStr } else { kv := strings.Split(res, "-") allowance, timestamp = kv[0], kv[1] } return } func GetRateLimitConfig() (limit, timeset int) { limit, _ = beego.AppConfig.Int("rateLimit") timeset, _ = beego.AppConfig.Int("rateTimeset") return } func SaveAllowance(ip, request, action, allowance, current string) { redisConfig := getRedisConfig() rs, err := cache.NewCache("redis", redisConfig) if err != nil { fmt.Println(err) return } rs.Put(ip "_" request, allowance "-" current, 600*time.Second) } func getRedisConfig() string { env := beego.AppConfig.String("runmode") conn := beego.AppConfig.String("redisConn") pass := beego.AppConfig.String("redisPass") name := beego.AppConfig.String("redisName") redisHash := make(map[string]interface{}) redisHash["conn"] = conn redisHash["key"] = name if env == "prod" { redisHash["password"] = pass } redisConfig, _ := json.Marshal(redisHash) return string(redisConfig) }</code></pre>
能够完全限制住接口的访问

<span style="font-size:18px">
</span>

到此这篇关于“Go实现接口访问速率限制”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
Go实现接口访问速率限制
(三)go-kit服务接口限流
Golang 限流器的使用和实现
go比php好在哪里
Go 开发关键技术指南 | 为什么你要选择 Go?(内含超全知识大图)
Go 语言到底适合干什么?
令牌桶算法如何使用php实现
第07章 Go语言接口(interface),Golang接口(interface)
go struct 成员变量后面再加个字符串是什么意思?_Go语言的学习笔记(第十章) 接口...
go 函数末尾缺少返回值_王垠:Go语言野心勃勃,实际情况又如何

[关闭]
~ ~