voucher/internal/pkg/limit/rate_test.go

34 lines
770 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package limit
import (
"golang.org/x/time/rate"
"testing"
"time"
)
func TestRateLimiter(t *testing.T) {
// 测试限流,连续多次请求 id=10
//p := &Parameters{
// Key: "key",
// Burst: 1,
// Interval: time.Second * 5,
//}
//n := NewRateLimiter()
//for i := 0; i < 11; i++ {
// err := n.RateLimit(p)
// if err != nil {
// t.Errorf("请求被限流,处理 id=%d ,错误信息:%v", i, err)
// } else {
// t.Logf("请求成功,处理 id=%d 的请求\n", i)
// }
// time.Sleep(1 * time.Second) // 每 1 秒请求一次
//}
limiter := rate.NewLimiter(rate.Every(time.Second), 100) // 每秒100个令牌突发容量100
if !limiter.Allow() {
// 拒绝或排队请求(需结合业务逻辑)
t.Log("限流")
return
}
}