Go实现接口访问速率限制

接口的访问限制,10分钟内,接口访问限制100次

基于go语言进行编写,抽离出统一配置。


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

能够完全限制住接口的访问


  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值