- 调整所有Go文件中的import语句顺序,使其符合标准库、第三方库、内部库的分类- 统一import语句的格式,去除多余的空行 - 确保所有文件中的import语句按照字母顺序和逻辑分组排列-修复部分文件中import语句缺失或重复的问题 -优化import语句的可读性和维护性
71 lines
1.6 KiB
Go
71 lines
1.6 KiB
Go
package limiter
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/duke-git/lancet/v2/slice"
|
|
"github.com/gogf/gf/v2/os/gmutex"
|
|
"github.com/gogf/gf/v2/os/gtime"
|
|
"github.com/gogf/gf/v2/util/gconv"
|
|
)
|
|
|
|
type Type string
|
|
|
|
const (
|
|
CardInfoJdAccountCookieChecker Type = "cardInfo:jd:account:cookie"
|
|
CardInfoJdAccountCookieSet Type = "cardInfo:jd:account:cookie:set"
|
|
CardInfoRedeemAccountCookieChecker Type = "cardInfo:account:cookie:checker"
|
|
CardInfoRedeemAccountCookieSet Type = "cardInfo:account:cookie:set"
|
|
)
|
|
|
|
func (t Type) Key(name interface{}) string {
|
|
return gconv.String(t) + ":" + gconv.String(name)
|
|
}
|
|
|
|
type simpleRateNode struct {
|
|
Key string
|
|
PutTime *gtime.Time
|
|
}
|
|
|
|
type SimpleLimiter struct {
|
|
mu gmutex.Mutex
|
|
rate []*simpleRateNode
|
|
Cap int
|
|
Expire int
|
|
}
|
|
|
|
// Allow 判断限流是否可用
|
|
func (l *SimpleLimiter) Allow(key string) bool {
|
|
l.checkAvailable()
|
|
if slice.CountBy(l.rate, func(index int, item *simpleRateNode) bool {
|
|
return item.Key == key
|
|
}) >= l.Cap {
|
|
return false
|
|
}
|
|
l.mu.LockFunc(func() {
|
|
l.rate = append(l.rate, &simpleRateNode{
|
|
Key: key,
|
|
PutTime: gtime.Now(),
|
|
})
|
|
})
|
|
return true
|
|
}
|
|
|
|
// CheckAvailable 判断所有节点是否可用
|
|
func (l *SimpleLimiter) checkAvailable() {
|
|
l.mu.LockFunc(func() {
|
|
l.rate = slice.Filter(l.rate, func(index int, item *simpleRateNode) bool {
|
|
return item.PutTime.After(gtime.Now().Add(time.Duration(-l.Expire) * gtime.S))
|
|
})
|
|
})
|
|
}
|
|
|
|
func NewSimpleLimiter(cap, expire int) *SimpleLimiter {
|
|
return &SimpleLimiter{
|
|
mu: gmutex.Mutex{},
|
|
Cap: cap,
|
|
Expire: expire,
|
|
rate: make([]*simpleRateNode, 0),
|
|
}
|
|
}
|