Documentation
¶
Overview ¶
Package mq 提供消息队列组件,支持 NATS JetStream 和 Redis Stream 两种后端。
MQ 组件是 Genesis L2 业务层组件,提供统一的发布-订阅接入方式,但不伪装成 两个驱动完全一致的语义。 设计原则:
- 简单优于复杂:核心接口精简,通过 Option 扩展能力
- 显式优于隐式:不做自动注入,用户完全掌控消息流
- 语义明确:持久 consumer/group 提供 At-least-once;Redis 广播模式 没有服务端消费进度或重投保证。Ack/Nak、QueueGroup、Durable、BatchSize 等细节保留各自差异
Example ¶
package main
import (
"context"
"time"
"github.com/ceyewan/genesis/connector"
"github.com/ceyewan/genesis/mq"
)
func main() {
ctx := context.Background()
conn, err := connector.NewRedis(&connector.RedisConfig{Addr: "localhost:6379"})
if err != nil {
return
}
defer conn.Close()
if err := conn.Connect(ctx); err != nil {
return
}
queue, err := mq.New(&mq.Config{Driver: mq.DriverRedisStream}, mq.WithRedisConnector(conn))
if err != nil {
return
}
defer queue.Close()
if err := queue.Publish(ctx, "orders", []byte(`{"id":42}`)); err != nil {
return
}
drainCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = queue.Drain(drainCtx)
}
Output:
Index ¶
- Constants
- Variables
- type Config
- type Driver
- type Handler
- type Headers
- type JetStreamConfig
- type MQ
- type Message
- type Middleware
- type Option
- type ProgressMessage
- type PublishOption
- type RedisStreamConfig
- type RetryConfig
- type StreamRetention
- type StreamStorage
- type SubscribeOption
- func FromBeginning() SubscribeOption
- func FromID(id string) SubscribeOption
- func FromLatest() SubscribeOption
- func WithAutoAck() SubscribeOption
- func WithBatchSize(size int) SubscribeOption
- func WithDurable(name string) SubscribeOption
- func WithManualAck() SubscribeOption
- func WithMaxInflight(n int) SubscribeOption
- func WithQueueGroup(name string) SubscribeOption
- type Subscription
Examples ¶
Constants ¶
const ( // DriverNATSJetStream NATS JetStream 驱动(持久化,支持 Ack/Nak 重投) DriverNATSJetStream Driver = "nats_jetstream" // DriverRedisStream Redis Stream 驱动(持久化,Consumer Group) DriverRedisStream Driver = "redis_stream" StreamRetentionLimits StreamRetention = "limits" StreamRetentionInterest StreamRetention = "interest" StreamRetentionWorkQueue StreamRetention = "work_queue" StreamStorageFile StreamStorage = "file" StreamStorageMemory StreamStorage = "memory" )
const ( // MetricPublishTotal 发布消息总数 MetricPublishTotal = "mq.publish.total" // MetricPublishDuration 发布延迟(秒) MetricPublishDuration = "mq.publish.duration" // MetricConsumeTotal 消费消息总数 MetricConsumeTotal = "mq.consume.total" // MetricHandleDuration 消息处理耗时(秒) MetricHandleDuration = "mq.handle.duration" )
指标名称常量
const ( // LabelTopic 主题标签 LabelTopic = "topic" // LabelStatus 状态标签(success/error) LabelStatus = "status" // LabelDriver 驱动标签 LabelDriver = "driver" )
标签名称常量
Variables ¶
var ( // ErrClosed MQ 已关闭 ErrClosed = xerrors.New("mq: client closed") // ErrInvalidConfig 配置无效 ErrInvalidConfig = xerrors.New("mq: invalid config") // ErrNotSupported 操作不支持 ErrNotSupported = xerrors.New("mq: operation not supported by this driver") // ErrSubscriptionClosed is retained for RC1 source compatibility. // // Deprecated: subscription shutdown is reported through Done, Drain, and // backend/context errors; no implementation returns this sentinel. ErrSubscriptionClosed = xerrors.New("mq: subscription closed") // ErrPanicRecovered Handler panic 已恢复 ErrPanicRecovered = xerrors.New("mq: handler panic recovered") )
预定义错误
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Driver 底层驱动类型,必填
// 可选值:nats_jetstream, redis_stream
Driver Driver `json:"driver" yaml:"driver" mapstructure:"driver"`
// JetStream JetStream 特有配置(仅 DriverNATSJetStream 时生效)
JetStream *JetStreamConfig `json:"jetstream,omitempty" yaml:"jetstream,omitempty" mapstructure:"jetstream"`
// RedisStream Redis Stream 特有配置(仅 DriverRedisStream 时生效)
RedisStream *RedisStreamConfig `json:"redis_stream,omitempty" yaml:"redis_stream,omitempty" mapstructure:"redis_stream"`
}
Config MQ 配置
type Handler ¶
Handler 消息处理函数
设计说明:只接收 Message 参数,通过 msg.Context() 获取上下文, 避免 ctx 与 msg.Context() 并存造成语义歧义。
返回值:
- nil: 处理成功,AutoAck 模式下自动调用 Ack
- error: 处理失败,AutoAck 模式下自动调用 Nak(Redis 下 ErrNotSupported 会被忽略)
注意(JetStream):Nak 触发消息立即重投,NakWithDelay 可请求延迟重投。对非暂时性错误(如解码失败), 建议使用 WithManualAck 手动 Ack,或配合 WithRetry 在应用层重试后 Ack, 避免消息无限重投。
type JetStreamConfig ¶
type JetStreamConfig struct {
// AutoCreateStream 是否自动创建 Stream(如果不存在)
// 生产环境建议关闭,通过运维手动创建并配置保留策略
AutoCreateStream bool `json:"auto_create_stream" yaml:"auto_create_stream" mapstructure:"auto_create_stream"`
// StreamPrefix Stream 名称前缀,默认 "S-"
StreamPrefix string `json:"stream_prefix" yaml:"stream_prefix" mapstructure:"stream_prefix"`
// AckWait 等待 Ack 的超时时间,超时后 JetStream 自动重投消息
// 默认 30s,应设置为业务 Handler 预期最大处理时间的 2 倍
AckWait time.Duration `json:"ack_wait" yaml:"ack_wait" mapstructure:"ack_wait"`
// MaxDeliver 是单条消息的最大投递次数,默认 5。达到上限后由应用根据
// JetStream advisory/DLQ 策略处理,Genesis 不定义业务死信主题。
MaxDeliver int `json:"max_deliver" yaml:"max_deliver" mapstructure:"max_deliver"`
// 以下字段仅用于 Genesis 自动创建的新 Stream。已存在 Stream 的运维配置会被保留。
Retention StreamRetention `json:"retention" yaml:"retention" mapstructure:"retention"`
Storage StreamStorage `json:"storage" yaml:"storage" mapstructure:"storage"`
MaxAge time.Duration `json:"max_age" yaml:"max_age" mapstructure:"max_age"`
MaxBytes int64 `json:"max_bytes" yaml:"max_bytes" mapstructure:"max_bytes"`
Replicas int `json:"replicas" yaml:"replicas" mapstructure:"replicas"`
}
JetStreamConfig JetStream 特有配置
type MQ ¶
type MQ interface {
// Publish 发布消息到指定主题
//
// 参数:
// - ctx: 上下文,用于超时控制和取消
// - topic: 非空消息主题(NATS subject / Redis stream key)
// - data: 消息体
// - opts: 发布选项(Headers 等)
Publish(ctx context.Context, topic string, data []byte, opts ...PublishOption) error
// Subscribe 订阅主题并处理消息
//
// Handler 签名:func(msg Message) error
// 通过 msg.Context() 获取上下文,避免参数冗余。
//
// 参数:
// - ctx: 订阅生命周期上下文,取消时自动停止订阅
// - topic: 非空订阅主题
// - handler: 非 nil 消息处理函数
// - opts: 订阅选项(QueueGroup、AutoAck 等)
Subscribe(ctx context.Context, topic string, handler Handler, opts ...SubscribeOption) (Subscription, error)
// Drain 停止接收新消息并等待所有已交付 Handler 完成。
// ctx 仅限制当前调用者的等待,不中断其他调用者共享的清理。
// 超时后可调用 Close 取消 Handler context;Go 无法强制终止忽略 context 的 Handler。
Drain(ctx context.Context) error
// Close 关闭 MQ 客户端
// 停止并等待已有及初始化中的订阅,最多等待 5 秒;超时不代表 Handler 已退出。
// 底层连接由 Connector 管理,不会被关闭。
Close() error
}
MQ 消息队列核心接口
提供统一的发布订阅入口,并保留底层驱动的语义差异。 当前支持的后端:NATS JetStream、Redis Stream。 JetStream durable 与 Redis consumer group 提供持久化和 At-least-once; Redis 广播模式只是读取 retained stream,不提供服务端重投语义。
type Message ¶
type Message interface {
// Context 获取消息处理上下文
//
// 该上下文继承自 Subscribe 调用时的 ctx,可用于:
// - 超时控制
// - 取消传播
// - 传递 trace 信息(需业务自行注入)
Context() context.Context
// Topic 获取消息主题
Topic() string
// Data 获取消息体(原始字节)
Data() []byte
// Headers 获取消息头(返回副本)
Headers() Headers
// Ack 确认消息处理成功
//
// 不同后端行为:
// - NATS JetStream: 发送 Ack 到服务端,消息从 pending 移除
// - Redis Stream: Consumer Group 模式下执行 XACK;广播模式下无操作
Ack() error
// Nak 拒绝消息,请求重投
//
// 不同后端行为:
// - NATS JetStream: 触发消息立即重投
// - Redis Stream: 返回 ErrNotSupported;消息留在 Pending 列表,
// 由 XAUTOCLAIM 在 PendingIdle 超时后重新认领
//
// 调用方应通过 errors.Is(err, ErrNotSupported) 区分"不支持"与真实错误。
// AutoAck 模式下 ErrNotSupported 会被自动忽略。
Nak() error
// NakWithDelay 拒绝消息并请求延迟重投。
// NATS JetStream 支持;Redis Stream 返回 ErrNotSupported。
NakWithDelay(delay time.Duration) error
// ID 获取消息唯一标识(可选)
//
// 不同后端返回值:
// - NATS JetStream: "<stream>:<sequence>"(如 "S-orders:42")
// - Redis Stream: 消息 ID(如 "1700000000000-0")
ID() string
}
Message 消息接口
封装底层消息细节,提供统一的数据访问和确认机制。 不同后端的 Ack/Nak 行为有差异,详见各方法注释。
type Middleware ¶
Middleware Handler 中间件
中间件模式允许在不修改业务逻辑的情况下增强 Handler 能力。 常见用途:重试、日志、链路追踪、指标等。
func Chain ¶
func Chain(middlewares ...Middleware) Middleware
Chain 将多个中间件串联成一个
执行顺序:第一个中间件最先执行,最后一个最接近原始 Handler。
示例:
handler = mq.Chain(logging, retry, tracing)(handler) // 执行顺序:logging -> retry -> tracing -> handler
func WithDeadLetter ¶
WithDeadLetter 创建死信队列中间件
当消息处理失败(所有重试都耗尽)后,将消息发送到死信队列。 这是跨驱动的通用实现,适用于 JetStream 和 Redis Stream。
参数:
- pub: MQ 实例,用于发送死信消息
- dlTopic: 死信队列主题
- maxRetries: 最大重试次数,超过后将消息发送到死信队列
- logger: 日志记录器
示例:
dlMiddleware := mq.WithDeadLetter(mqClient, "orders.DLQ", 3, logger) handler = dlMiddleware(myHandler)
func WithLogging ¶
func WithLogging(logger clog.Logger) Middleware
WithLogging 创建日志中间件
记录每条消息的处理情况,包括:topic、消息 ID、处理耗时、错误信息。
func WithRecover ¶
func WithRecover(logger clog.Logger) Middleware
WithRecover 创建 panic 恢复中间件
捕获 Handler 中的 panic,转换为错误返回,避免整个消费者崩溃。
func WithRetry ¶
func WithRetry(cfg RetryConfig, logger clog.Logger) Middleware
WithRetry 创建重试中间件
在应用层实现重试逻辑(不依赖 MQ 后端的重投机制)。 适用于幂等操作或可安全重试的场景。
注意:
- 重试发生在单次消息处理内,不影响 MQ 层面的 Ack/Nak
- 如果所有重试都失败,最终错误会返回给上层(可能触发 Nak)
示例:
handler := mq.WithRetry(mq.DefaultRetryConfig(), logger)(myHandler)
type Option ¶
type Option func(*options)
Option MQ 配置选项
func WithNATSConnector ¶
func WithNATSConnector(conn connector.NATSConnector) Option
WithNATSConnector 注入 NATS 连接器(用于 NATS Core / JetStream)
func WithRedisConnector ¶
func WithRedisConnector(conn connector.RedisConnector) Option
WithRedisConnector 注入 Redis 连接器(用于 Redis Stream)
type ProgressMessage ¶ added in v1.0.0
type ProgressMessage interface {
InProgress() error
}
ProgressMessage 是长耗时消息处理的可选心跳能力。
NATS JetStream 消息实现该接口;InProgress 会重置服务端 AckWait 计时器。 Redis Stream 消息不实现它。调用方应对 Message 做类型断言,不要假设所有驱动都支持。
type PublishOption ¶
type PublishOption func(*publishOptions)
PublishOption 发布选项
func WithHeaders ¶
func WithHeaders(h Headers) PublishOption
WithHeaders 设置消息头
示例:
mq.Publish(ctx, "topic", data, mq.WithHeaders(mq.Headers{
"trace-id": "abc123",
}))
type RedisStreamConfig ¶
type RedisStreamConfig struct {
// MaxLen Stream 最大长度,0 表示不限制,超过后自动裁剪旧消息
MaxLen int64 `json:"max_len" yaml:"max_len" mapstructure:"max_len"`
// Approximate 是否使用近似裁剪(MAXLEN ~),开启后性能更好但长度控制不精确
Approximate bool `json:"approximate" yaml:"approximate" mapstructure:"approximate"`
// PendingIdle 消息在 Pending 列表中的最大空闲时间,超过后可被其他消费者认领
// 用于处理消费者崩溃导致消息卡住的场景
// 默认 30s,应设置为业务 Handler 预期最大处理时间的 2 倍
PendingIdle time.Duration `json:"pending_idle" yaml:"pending_idle" mapstructure:"pending_idle"`
}
RedisStreamConfig Redis Stream 特有配置
type RetryConfig ¶
type RetryConfig struct {
// MaxRetries 最大重试次数(不含首次执行)
MaxRetries int `json:"max_retries" yaml:"max_retries" mapstructure:"max_retries"`
// InitialBackoff 初始退避时间
InitialBackoff time.Duration `json:"initial_backoff" yaml:"initial_backoff" mapstructure:"initial_backoff"`
// MaxBackoff 最大退避时间
MaxBackoff time.Duration `json:"max_backoff" yaml:"max_backoff" mapstructure:"max_backoff"`
// Multiplier 退避倍数
Multiplier float64 `json:"multiplier" yaml:"multiplier" mapstructure:"multiplier"`
}
RetryConfig 重试配置
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns a fresh default configuration. Returning a value avoids mutable process-global retry behavior.
type StreamRetention ¶ added in v1.0.0
type StreamRetention string
type StreamStorage ¶ added in v1.0.0
type StreamStorage string
type SubscribeOption ¶
type SubscribeOption func(*subscribeOptions)
SubscribeOption 订阅选项
func FromBeginning ¶ added in v1.0.0
func FromBeginning() SubscribeOption
FromBeginning consumes retained messages when a subscription or durable consumer is created for the first time. This is the default.
func FromID ¶ added in v1.0.0
func FromID(id string) SubscribeOption
FromID starts at a backend message ID. Redis accepts stream IDs; JetStream accepts Genesis IDs such as "S-orders:42" and uses the numeric sequence.
func FromLatest ¶ added in v1.0.0
func FromLatest() SubscribeOption
FromLatest starts after messages that already exist at first subscription.
func WithAutoAck ¶
func WithAutoAck() SubscribeOption
WithAutoAck 开启自动确认
启用后 Handler 返回 nil 时自动 Ack,返回 error 时自动 Nak。 注意:这会改变默认行为,确保业务逻辑能正确处理。
func WithBatchSize ¶
func WithBatchSize(size int) SubscribeOption
WithBatchSize 设置批量拉取大小
影响单次拉取的消息数量,适当增大可提升吞吐量。 默认值:10
驱动支持情况:
- Redis Stream:有效,对应 XREADGROUP COUNT / XREAD COUNT 参数。
- JetStream:对应当前订阅实例的 PullMaxMessages,不会改写共享 durable。
func WithDurable ¶
func WithDurable(name string) SubscribeOption
WithDurable 设置消费者实例名称
驱动映射(语义不同,请注意区分):
- NATS JetStream: 作为 durable consumer 的逻辑名称;实现会按 topic 添加稳定后缀, 避免同一 stream 内多个 topic 共用名称时互相改写 FilterSubject。 未设置 WithQueueGroup 时生效,设置后 WithQueueGroup 优先。
- Redis Stream: 映射为 consumer name,是同一 group 内消费者实例的标识; 需与 WithQueueGroup 配合使用,单独设置无持久化效果。
如需跨驱动共享消费进度,请使用 WithQueueGroup。
func WithManualAck ¶
func WithManualAck() SubscribeOption
WithManualAck 关闭自动确认(默认行为)
启用后需要在 Handler 中手动调用 msg.Ack() 或 msg.Nak()。 适用于需要精确控制确认时机的场景。
重要说明(JetStream):
- 调用 msg.Nak() 会触发消息重新投递
- 对于无法恢复的错误,应该 Ack() 而非 Nak(),避免无限循环
- 建议配合 WithRetry 中间件在应用层重试
func WithMaxInflight ¶
func WithMaxInflight(n int) SubscribeOption
WithMaxInflight 设置最大在途消息数
限制共享 durable consumer 的未确认消息总数,用于集群级背压控制。 仅 JetStream 有效(对应 MaxAckPending);同一 durable 的所有订阅实例共享该值。
func WithQueueGroup ¶
func WithQueueGroup(name string) SubscribeOption
WithQueueGroup 设置消费组(用于竞争消费/负载均衡)
同一消费组内的消费者竞争消费消息,实现负载均衡。 不设置时为独立消费(广播)模式。
驱动映射(语义有差异):
- NATS JetStream: 映射为 durable consumer 名称,多实例共享同一 durable 实现负载均衡
- Redis Stream: 映射为 consumer group 名称,组是持久化进度的承载体
注意:两者"持久化"的载体不同,JetStream 持久化在 durable consumer,Redis 持久化在 group。
type Subscription ¶
type Subscription interface {
// Unsubscribe 取消订阅
//
// 调用后停止接收新消息。
// 注意:不保证等待当前 Handler 完成,具体行为依赖后端实现。
Unsubscribe() error
// Drain 停止接收新消息并等待已经交付的 Handler 完成。
// ctx 取消时会取消 Handler context 并返回 context 错误;忽略 context 的
// Handler 无法被 Go 运行时强制终止,可能在返回后继续运行。
Drain(ctx context.Context) error
// Done 返回一个 channel,订阅结束时关闭
//
// 可用于等待订阅完全停止:
// sub.Unsubscribe()
// <-sub.Done()
Done() <-chan struct{}
}
Subscription 订阅句柄
用于管理订阅的生命周期。