Go實現介面訪問速率限制

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

介面的訪問限制,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 / timesetif 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"] = connredisHash["key"] = nameif env == "prod" {redisHash["password"] = pass}redisConfig, _ := json.Marshal(redisHash)return string(redisConfig)}

能夠完全限制住介面的訪問


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.