2 Star 9 Fork 1

os-lee/easy-paas

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
flow_qps_count.go 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
lee 提交于 2024-07-11 15:01 . websocket路由支持url重写,负载均衡
package middleware_http
import (
"errors"
"gitee.com/os-lee/easy-paas/common"
"gitee.com/os-lee/easy-paas/common/e"
"gitee.com/os-lee/easy-paas/common/flow"
"gitee.com/os-lee/easy-paas/common/logger"
"gitee.com/os-lee/easy-paas/gateway/internal/cache"
"gitee.com/os-lee/easy-paas/gateway/internal/dao"
"github.com/gin-gonic/gin"
"time"
)
// FlowQpsCount 统计QPS
func FlowQpsCount() gin.HandlerFunc {
return func(c *gin.Context) {
serverInterface, ok := c.Get("service")
if !ok {
common.ResponseError(c, e.ErrGateway, errors.New("从上下文中获取服务失败"))
c.Abort()
return
}
// 统计网关QPS
qwCounter := flow.QpsCounterHandler.GetQpsCounterItem(common.EasyGatewayQps, cache.RedisCli)
qwCounter.Requests++ // 增加请求计数
// 按服务统计QPS
serviceDetail := serverInterface.(*dao.ServiceDetail)
serviceName := serviceDetail.Info.ServiceName
svcCounter := flow.QpsCounterHandler.GetQpsCounterItem(serviceName, cache.RedisCli)
svcCounter.Requests++ // 增加请求计数
c.Next() // 继续处理请求
// 在请求结束后计算网关QPS
if time.Since(qwCounter.StartTime) >= time.Second {
qps := float64(qwCounter.Requests) / time.Since(qwCounter.StartTime).Seconds()
// 写入redis
err := qwCounter.WriteQPS(c, qps)
if err != nil {
// 写入QPS错误,不影响业务,记录日志即可
logger.Log.Errorf("将QPS写入redis错误, Err: %v", err)
}
qwCounter.Requests = 0 // 重置计数器
qwCounter.StartTime = time.Now() // 更新开始时间
}
// 在请求结束后计算各服务QPS
if time.Since(svcCounter.StartTime) >= time.Second {
qps := float64(svcCounter.Requests) / time.Since(svcCounter.StartTime).Seconds()
// 写入redis
err := svcCounter.WriteQPS(c, qps)
if err != nil {
// 写入QPS错误,不影响业务,记录日志即可
logger.Log.Errorf("将QPS写入redis错误, Err: %v", err)
}
svcCounter.Requests = 0 // 重置计数器
svcCounter.StartTime = time.Now() // 更新开始时间
}
}
}
马建仓 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
b4985bcf7af8

搜索帮助