1 Star 1 Fork 0

tuboyou / interfacego

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
sync.go 1002 Bytes
一键复制 编辑 原始数据 按行查看 历史
李学成 提交于 2022-02-11 20:10 . 添加同步校验
package sync
import (
"sync"
"time"
)
//经试验当前最高支持200wQPS
var lock sync.RWMutex
type Limit struct {
times int
num int
now int64
interval int
stop bool
timemap map[int64]int64
}
func (l *Limit) Stop() {
l.stop = true
}
func (l *Limit) GetStop() bool {
return l.stop
}
func Limiter(times int) *Limit {
if times < 0 {
panic("限制出错,不能小于1")
}
if times == 0 {
times = 1
}
l := &Limit{
times: times,
now: -1,
interval: 1e7 / (times + 5),
timemap: make(map[int64]int64),
}
return l
}
func (l *Limit) TimeLine() map[int64]int64 {
return l.timemap
}
func (l *Limit) Get() {
lock.Lock()
defer lock.Unlock()
now := time.Now().Unix()
if l.now == now {
if l.num < l.times {
l.num++
time.Sleep(time.Duration(l.interval))
l.timemap[l.now] += 1
return
} else {
next := time.Unix(now+1, -100)
time.Sleep(time.Until(next))
now = now + 1
}
}
l.now = now
l.num = 1
l.timemap[l.now] += 1
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/tuboyou/interfacego.git
git@gitee.com:tuboyou/interfacego.git
tuboyou
interfacego
interfacego
v0.0.3

搜索帮助

344bd9b3 5694891 D2dac590 5694891