golang 限流

golang 如何对高并发的场景进行限流

import 	"golang.org/x/time/rate"

// 每秒最多30次放行
var l = rate.NewLimiter(1, 30)

func TestExecLimit2(t *testing.T) {
    
    
	runtime.GOMAXPROCS(runtime.NumCPU())

	go func() {
    
    
		for {
    
    
			ExecLimit2(l, func() {
    
    
				fmt.Println("do")
			})
		}
	}()

	select {
    
    
	case <-time.After(1 * time.Second):
		fmt.Println("1秒到时")
	}
}


func ExecLimit2(l *rate.Limiter, f func()) {
    
    
	go func() {
    
    
		l.Wait(context.Background())
		f()
	}()
}

限流中间件

func LimitRate(r *rate.Limiter) gin.HandlerFunc {
    
    
	return func(c *gin.Context) {
    
    
		r.Wait(context.Background())
		c.Next()
	}
}

使用

var l = rate.New(1,50)
// 购买接口1秒内只允许50个请求
r.POST("/second-kill-shop/buy/", LimitRate(l), buyShop)

猜你喜欢

转载自blog.csdn.net/fwhezfwhez/article/details/112895756