1. 程式人生 > 程式設計 >golang介面IP限流,IP黑名單,IP白名單的例項

golang介面IP限流,IP黑名單,IP白名單的例項

增加中介軟體

可以選擇普通模式和LUA指令碼模式,建議選擇普通模式,實際上不需要控制的那麼精確。

package Middlewares
import (
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"voteapi/pkg/app/response"
	"voteapi/pkg/gredis"
	"voteapi/pkg/util"
)
const IP_LIMIT_NUM_KEY = "ipLimit:ipLimitNum"
const IP_BLACK_LIST_KEY = "ipLimit:ipBlackList"
var prefix = "{gateway}"
var delaySeconds int64 = 60  // 觀察時間跨度,秒
var maxAttempts int64 = 10000 // 限制請求數
var blackSeconds int64 = 0  // 封禁時長,秒,0-不封禁
func GateWayPlus() gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.FullPath()
		clientIp := c.ClientIP()
		// redis配置叢集時必須
		param := make(map[string]string)
		param["path"] = path
		param["clientIp"] = clientIp
		if !main(param) {
			c.Abort()
			response.JsonResponseError(c,"當前IP請求過於頻繁,暫時被封禁~")
		}
	}
}
func main(param map[string]string) bool {
	// 預知的IP黑名單
	var blackList []string
	if util.InStringArray(param["clientIp"],blackList) {
		return false
	}
	// 預知的IP白名單
	var whiteList []string
	if util.InStringArray(param["clientIp"],whiteList) {
		return false
	}
	blackKey := prefix + ":" + IP_BLACK_LIST_KEY
	limitKey := prefix + ":" + IP_LIMIT_NUM_KEY
	curr := time.Now().Unix()
	item := util.Md5(param["path"] + "|" + param["clientIp"])
	return normal(blackKey,limitKey,item,curr)
}
// 普通模式
func normal(blackKey string,limitKey string,item string,time int64) (res bool) {
	if blackSeconds > 0 {
		timeout,_ := gredis.RawCommand("HGET",blackKey,item)
		if timeout != nil {
			to,_ := strconv.Atoi(string(timeout.([]uint8)))
			if int64(to) > time {
				// 未解封
				return false
			}
			// 已解封,移除黑名單
			gredis.RawCommand("HDEL",item)
		}
	}
	l,item)
	if l != nil {
		last,_ := strconv.Atoi(string(l.([]uint8)))
		if int64(last) >= maxAttempts {
			return false
		}
	}
	num,_ := gredis.RawCommand("HINCRBY",1)
	if ttl,_ := gredis.TTLKey(limitKey); ttl == int64(-1) {
		gredis.Expire(limitKey,int64(delaySeconds))
	}
	if num.(int64) >= maxAttempts && blackSeconds > 0 {
		// 加入黑名單
		gredis.RawCommand("HSET",time+blackSeconds)
		// 刪除記錄
		gredis.RawCommand("HDEL",item)
	}
	return true
}
// LUA指令碼模式
// 支援redis叢集部署
func luaScript(blackKey string,time int64) (res bool) {
	script := `
local blackSeconds = tonumber(ARGV[5])
if(blackSeconds > 0)
then
  local timeout = redis.call('hget',KEYS[1],ARGV[1])
  if(timeout ~= false)
  then
    if(tonumber(timeout) > tonumber(ARGV[2]))
    then
      return false
    end
    redis.call('hdel',ARGV[1])
  end
end
local last = redis.call('hget',KEYS[2],ARGV[1])
if(last ~= false and tonumber(last) >= tonumber(ARGV[3]))
then
  return false
end
local num = redis.call('hincrby',ARGV[1],1)
local ttl = redis.call('ttl',KEYS[2])
if(ttl == -1)
then
  redis.call('expire',ARGV[4])
end
if(tonumber(num) >= tonumber(ARGV[3]) and blackSeconds > 0)
then 
  redis.call('hset',ARGV[2] + ARGV[5])
  redis.call('hdel',ARGV[1])
end
return true
`
	result,err := gredis.RawCommand("EVAL",script,2,time,maxAttempts,delaySeconds,blackSeconds)
	if err != nil {
		return false
	}
	if result == int64(1) {
		return true
	} else {
		return false
	}
}

補充:golang實現限制每秒多少次的限頻操作

前言

一些函式的執行可能會限制頻率,比如某個api介面要求每秒最大請求30次。下面記錄了自己寫的限頻和官方的限頻

程式碼

// 加鎖限頻,輸出次數大概率小於最大值
func ExecLimit(lastExecTime *time.Time,l *sync.RWMutex,maxTimes int,perDuration time.Duration,f func()) {
  l.Lock()
  defer l.Unlock()
 // per times cost time(s)
 SecondsPerTimes := float64(perDuration) / float64(time.Second) / float64(maxTimes)
 now := time.Now()
 interval := now.Sub(*lastExecTime).Seconds()
 if interval < SecondsPerTimes {
 time.Sleep(time.Duration(int64((SecondsPerTimes-interval)*1000000000)) * time.Nanosecond)
 }
 f()
 *lastExecTime = time.Now()
}
// 官方的,需要引用 "golang.org/x/time/rate"
// 基本上可以達到滿值,比自己寫的更優
func ExecLimit2(l *rate.Limiter,f func()) {
 go func() {
 l.Wait(context.Background())
 f()
 }()
}

使用

func TestExecLimit(t *testing.T) {
 runtime.GOMAXPROCS(runtime.NumCPU())
 go func() {
 var lastExecTime time.Time
 var l sync.RWMutex
 for {
  ExecLimit(&lastExecTime,&l,10,time.Second,func() {
  fmt.Println("do")
  })
 }
 }()
 select {
 case <-time.After(1 * time.Second):
 fmt.Println("1秒到時")
 }
}
func TestExecLimit2(t *testing.T) {
 runtime.GOMAXPROCS(runtime.NumCPU())
 l := rate.NewLimiter(1,30)
 go func() {
 for {
      ExecLimit2(l,func() {
  fmt.Println("do")
  })
 }
 }()
 select {
 case <-time.After(1 * time.Second):
 fmt.Println("1秒到時")
 }
}

輸出:

一秒內輸出了<=10次 "do"

如何在多節點服務中限制頻

上述使用,定義在某個服務節點的全域性變數lastExecTime僅僅會對該服務的函式f()操作限頻,如果在負載均衡後,多個相同服務的節點,對第三方的介面累計限頻,比如三個服務共同拉取第三方介面,合計限頻為30次/s.

則,必須將lastExecTime的獲取,從redis等共享中介軟體中獲取,而不應該從任何一個單點服務獲取。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。