高精度 QPS 统计系统,适用于高并发场景的实时请求频率统计。基于 Go 语言实现的高性能计数器,支持百万级 QPS 场景下的精确统计。
+-------------------+ +-----------------------+
| HTTP Server | ⇒ | Adaptive Sharding |
| (net/http,fasthttp)| +-----------------------+
+-------------------+
↓ ↓
+---------------+ +------------------------+
| Lock-Free 引擎 | | Sharded 计数器集群 |
| (CAS 原子操作) | | (动态分片) |
+---------------+ +------------------------+
⇓
+------------------------------------------------+
| 动态分片管理器 |
| • 10 秒间隔监控 QPS 变化率(±30%触发调整) |
| • 分片数自动伸缩(最小 CPU 核心数,最大 CPU 核心数*8 )|
| • 内存使用监控(自动调整分片以优化内存使用) |
+------------------------------------------------+
⇓
+------------------+ +------------------+ +------------------+
| 限流保护层 | | 监控指标层 | | 优雅关闭机制 |
| (令牌桶+自适应) | | (Prometheus 集成) | | (请求完整性保障) |
+------------------+ +------------------+ +------------------+
基于原子操作( CAS )实现的无锁计数器,适用于中等流量场景:
atomic.Int64
实现无锁计数,避免高并发下的锁竞争分片设计的高性能计数器,适用于超高并发场景:
runtime.NumCPU() * 4
server:
port: 8080
read_timeout: 5s
write_timeout: 10s
server_type: fasthttp # HTTP 服务器类型( standard/fasthttp )
counter:
type: "lockfree" # 计数器类型( lockfree/sharded )
window_size: 1s # 统计时间窗口
slot_num: 10 # 窗口分片数量
precision: 100ms # 统计精度
limiter:
enabled: true # 是否启用限流
rate: 1000000 # 每秒允许的请求数
burst: 10000 # 突发请求容量
adaptive: true # 是否启用自适应限流
metrics:
enabled: true # 是否启用指标收集
interval: 5s # 指标收集间隔
endpoint: "/metrics" # 指标暴露端点
shutdown:
timeout: 30s # 优雅关闭超时时间
max_wait: 60s # 最大等待时间
logger:
level: info
format: json
file_path: "/var/log/qps-counter/app.log"
max_size: 100
max_backups: 3
max_age: 7
服务器类型 | 并发量 | 平均延迟 | P99 延迟 | QPS |
---|---|---|---|---|
standard | 10k | 1.8ms | 4.5ms | 850k |
fasthttp | 10k | 1.2ms | 3.5ms | 950k |
高负载场景测试结果: | 服务器类型 | 并发量 | 平均延迟 | P99 延迟 | QPS | |------------|--------|---------|--------|--------| | standard | 100k | 2.5ms | 6.5ms | 1.05M | | fasthttp | 100k | 1.2ms | 3.5ms | 1.23M |
go get github.com/mant7s/qps-counter
package main
import (
"github.com/mant7s/qps-counter/counter"
"log"
)
func main() {
// 创建计数器实例
cfg := counter.DefaultConfig()
counter, err := counter.NewCounter(cfg)
if err != nil {
log.Fatal(err)
}
// 增加计数
counter.Increment()
// 获取当前 QPS
qps := counter.GetQPS()
log.Printf("Current QPS: %d", qps)
}
系统通过/metrics
端点暴露 Prometheus 格式的监控指标:
qps_counter_requests_total
: 总请求计数qps_counter_current_qps
: 当前 QPS 值qps_counter_memory_usage_bytes
: 内存使用量qps_counter_cpu_usage_percent
: CPU 使用率qps_counter_goroutines
: Goroutine 数量qps_counter_request_duration_seconds
: 请求处理时间分布git clone https://github.com/mant7s/qps-counter.git
cd qps-counter
go mod download
make test
make build
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.