You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取jetstream.Msg消息的当前处理尝试次数以实现渐进式超时?

获取Jetstream.Msg的当前处理尝试次数

Jetstream 的 jetstream.Msg 本身没有直接暴露获取处理尝试次数的方法,但可以通过消息的Headers获取NATS自动注入的投递计数,以此实现渐进式超时逻辑。

核心思路

NATS Jetstream会为每一条投递的消息自动添加 Nats-Delivered-Count 头字段,该字段的值从1开始递增,每次消息被重新投递(比如Nak后)都会加1,这个值就是当前的处理尝试次数。

代码实现示例

import (
    "strconv"
    "time"
    "github.com/nats-io/nats.go/jetstream"
)

func handler(msg jetstream.Msg) {
    // 从Headers中获取投递次数
    countStr := msg.Headers().Get("Nats-Delivered-Count")
    attemptCount, err := strconv.Atoi(countStr)
    if err != nil {
        // 解析失败时默认设为第一次尝试
        attemptCount = 1
    }

    // 根据尝试次数计算渐进式延迟(示例为线性递增:第N次尝试延迟N*10秒)
    delay := time.Duration(attemptCount) * time.Second * 10

    err = doWork()
    if err != nil {
        _ = msg.NakWithDelay(delay)
        return
    }

    _ = msg.Ack()
}

注意事项

  • Nats-Delivered-Count 是Jetstream自动注入的头字段,无需手动添加
  • 第一次投递时该字段值为1,每一次重新投递都会自动加1
  • 如果消息原本没有Headers,Jetstream会自动创建Headers并添加该字段

内容的提问来源于stack exchange,提问作者AlexandrT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 06:17:10