目录

Counter 调用次数

实时队列长度

Gauge 和队列长度区别和优缺点对比

📌 举例说明差异

你用 ask_queue.qsize() 的情况:

你用 Gauge.set(ask_queue.qsize()) 的情况:

CollectorRegistry 注册方式实例化


Counter 调用次数

from prometheus_client import start_http_server, Counter

# 定义一个计数器
REQUESTS = Counter('requests_total', 'Total number of requests')

def main():
    # 启动 Prometheus HTTP 服务,默认端口 8000
    start_http_server(8000)

    # 模拟请求
    while True:
        REQUESTS.inc()  # 每次调用增加 1
        time.sleep(1)

if __name__ == '__main__':
    main()

实时队列长度

from prometheus_client import Gauge, start_http_server
import time
import queue

# 创建注册表(可选)
from prometheus_client import CollectorRegistry
registry_1 = CollectorRegistry()

# 定义 Gauge 指标
QUEUE_GAUGE = Gauge('LiveAsrServiceQueueSize', 'current queue size of live asr', registry=registry_1)

# 假设你的实时队列
task_queue = queue.Queue()

# 模拟添加任务
def add_task():
    task_queue.put("audio_data")

# 模拟处理任务
def process_task():
    if not task_queue.empty():
        task_queue.get()

# 定期更新 Prometheus 指标
def update_metrics():
    queue_size = task_queue.qsize()
    QUEUE_GAUGE.set(queue_size)  # 设置当前队列长度

if __name__ == "__main__":
    # 启动 Prometheus 的 HTTP 服务
    start_http_server(8000, registry=registry_1)

    # 模拟生产消费过程
    while True:
        add_task()               # 模拟请求进来
        process_task()           # 模拟处理请求
        update_metrics()         # 更新队列大小指标
        time.sleep(1)            # 每秒更新一次

Gauge 和队列长度区别和优缺点对比

特性 ask_queue.qsize() prometheus_client.Gauge
定义 Python 标准库 queue.Queue 提供的当前元素数量 Prometheus 指标类型,用于暴露数值型状态
调用位置 代码内部使用(只能在当前进程里访问) 暴露为 Web 接口,供外部系统采集
可视化 ❌ 不能用于监控图表 ✅ 可接入 Prometheus + Grafana 监控
历史记录 ❌ 只返回当前值,没有历史 ✅ Prometheus 会定时抓取并存储,支持趋势分析
报警机制 ❌ 无法设置阈值报警 ✅ 可设置如“队列长度 > 100 报警”规则
用途 程序逻辑内部判断是否要消费/等待 运维监控、服务健康状况展示、预警系统
性能影响 极低(直接访问队列) 轻微增加(需要暴露 HTTP 接口)


📌 举例说明差异

你用 ask_queue.qsize() 的情况:

if ask_queue.qsize() > 100: print("队列过长,暂停接收任务")

→ 用于程序运行时控制逻辑,不对外公开,开发者调试用。


你用 Gauge.set(ask_queue.qsize()) 的情况:

QUEUE_GAUGE.set(ask_queue.qsize())

→ Prometheus 会定时抓取,记录下来,配合 Grafana 画图并做告警分析:

  • 查看队列高峰时间段;

  • 队列是否慢慢在积压;

  • qsize()代码内部用来判断当前状态

  • prometheus_client.Gauge.set(qsize())用来将这个状态暴露给监控系统

它们不是替代关系,而是搭配使用的:你先用 qsize() 得到数据,再通过 Gauge 让别人能看到这数据。

CollectorRegistry 注册方式实例化

from prometheus_client import Counter, generate_latest, CollectorRegistry, multiprocess, CONTENT_TYPE_LATEST, make_asgi_app, Gauge

registry = CollectorRegistry()
# 定义 Prometheus 指标
CALL_COUNT = Counter(
    "live_asr_me", 
    "part3 Total number of method calls",
    ["method", "status"],registry=registry
)

registry_1 = CollectorRegistry(auto_describe=True)

QUEUE_GAUGE = Gauge('LiveceQueueSize', 'curasr', registry=registry_1)

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐