3 Star 9 Fork 1

os-lee/easy-paas

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
qps_counter.go 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
lee 提交于 2024-07-09 19:23 . 使用gobreaker支持服务熔断功能
package flow
import (
"context"
"fmt"
"gitee.com/os-lee/easy-paas/common"
"github.com/go-redis/redis/v8"
"strconv"
"sync"
"time"
)
// QpsCounterHandler QPS计算器
var (
QpsCounterHandler *QpsCounter
)
func init() {
QpsCounterHandler = newQpsCounter()
}
type QpsCounter struct {
QpsCounterMap sync.Map
}
func newQpsCounter() *QpsCounter {
return &QpsCounter{
QpsCounterMap: sync.Map{},
}
}
type QpsCounterItem struct {
RedisCli *redis.Client
serviceName string
Requests int64 // 请求计数
StartTime time.Time // 开始时间
}
func newQpsCounterItem(serviceName string, redisCli *redis.Client) *QpsCounterItem {
return &QpsCounterItem{
RedisCli: redisCli,
serviceName: serviceName,
Requests: 0,
StartTime: time.Now(),
}
}
func (qc *QpsCounter) GetQpsCounterItem(serviceName string, redisCli *redis.Client) *QpsCounterItem {
if value, ok := qc.QpsCounterMap.Load(serviceName); ok {
return value.(*QpsCounterItem)
}
item := newQpsCounterItem(serviceName, redisCli)
qc.QpsCounterMap.Store(serviceName, item)
return item
}
func (qci *QpsCounterItem) WriteQPS(ctx context.Context, qps float64) error {
// 写入网关当前QPS
gwKey := fmt.Sprintf("%s_%s", common.ReqCounterByService, common.EasyGatewayReq)
err := qci.RedisCli.Set(ctx, gwKey,
strconv.FormatFloat(qps, 'f', 2, 64), 5*time.Second).Err()
// 写入各业务QPS
svcKey := fmt.Sprintf("%s_%s", common.ReqCounterByService, qci.serviceName)
err = qci.RedisCli.Set(ctx, svcKey,
strconv.FormatFloat(qps, 'f', 2, 64), 5*time.Second).Err()
return err
}
func (qci *QpsCounterItem) GetQps(ctx context.Context) (string, error) {
key := fmt.Sprintf("%s_%s", common.ReqCounterByService, qci.serviceName)
return qci.RedisCli.Get(ctx, key).Result()
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/os-lee/easy-paas.git
git@gitee.com:os-lee/easy-paas.git
os-lee
easy-paas
easy-paas
6cf1638f64c0

搜索帮助