event

package
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2026 License: MIT Imports: 4 Imported by: 0

README

event

跨进程事件总线抽象与 Redis Stream 风格实现。

语义

  • Publish:写入流(topic)
  • Subscribe:按 consumer group 独立消费;同一 topic 上每个 group 都会收到副本(fan-out)
  • Handler 须幂等
业务异常 vs 通信异常
类型 用法 框架 ACK
业务异常 业务自行 log 后 return nil;或 return err 仅供框架打印 ACK(不重试)
通信异常 return event.NoAck(err)(DB/Redis/超时等) 不 ACK,pending 重试
// 业务:缺套餐 —— 只记日志,流程算处理完
log.Infof("skip: plan missing")
return nil

// 通信:写库失败 —— 控制 ACK
return event.NoAck(fmt.Errorf("db: %w", err))

用法

bus := redisstream.New(backend, "event") // Bus 默认 MAXLEN ~ 10000(Envelope.MaxLen==0 时)
_ = bus.Publish(ctx, "org.certified", event.Envelope{
	Type: "org.certified", Payload: payloadJSON, MaxLen: 10000,
})

// 单 topic(每订阅一个 goroutine / 一条 BLOCK 连接)
_ = bus.Subscribe(ctx, "org.certified", "my-service", "instance-1", handler)

// 多 topic:链式 On + Run;单循环多 Stream XREADGROUP BLOCK,handler 走 gopool
_ = bus.Consumer("my-service", "instance-1").
	On("org.certified", handleOrgCertified).
	On("order.purchased", handleOrderPurchased).
	Run(ctx)

Consumer 默认 handler 池 min=2 max=8(WithHandlerWorkers / WithHandlerPool 可改)。

业务目录用 event.Def 把类型与 MaxLen 写在一起(见 internal/ddd/events):

EventOrgCertified = event.Def{Type: "org.certified", MaxLen: 10000}

Backend 由基础设施适配具体 Redis 客户端,本包不绑定驱动。

留存

Publish 经 Backend.XAdd(..., maxLen) 近似封顶(Redis:MAXLEN ~):

优先级 来源
1 Envelope.MaxLen(>0,通常来自 event.Def)
2 Bus:DefaultMaxLen / WithMaxLen / EVENT_STREAM_MAXLEN

Stream 是投递缓冲,不是业务存档;业务结果落库。

Documentation

Overview

Package event 提供跨进程事件总线抽象:发布 / 按消费者组订阅。

本包不含业务事件名或载荷定义;业务目录放在使用方。

Handler 两类结果:

  • 业务结果:自行打日志后 return nil;若 return 普通 error,框架仅打印后 ACK(不重试)
  • 通信/基础设施失败:return event.NoAck(err),框架不 ACK,保留 pending 重试

Handler 须幂等。

Index

Constants

This section is empty.

Variables

View Source
var Debug = false

Functions

func IsNoAck

func IsNoAck(err error) bool

IsNoAck 是否为控制 ACK 的通信异常(含 wrap 链)。

func IsNonIgnorable deprecated

func IsNonIgnorable(err error) bool

Deprecated: 使用 IsNoAck。

func NoAck

func NoAck(err error) error

NoAck 包装通信层异常,控制 ACK(不确认、可重试)。err 为 nil 时返回 nil。

func NoAckf

func NoAckf(format string, args ...any) error

NoAckf 同 NoAck,带格式化。

func NonIgnorable deprecated

func NonIgnorable(err error) error

Deprecated: 使用 NoAck。

func NonIgnorableF deprecated

func NonIgnorableF(format string, args ...any) error

Deprecated: 使用 NoAckf。

func SetDebug

func SetDebug(debug bool)

Types

type Backend

type Backend interface {
	// XAdd 写入流。maxLen>0 时近似封顶(如 Redis MAXLEN ~);0 不裁剪。
	XAdd(ctx context.Context, stream string, values map[string]string, maxLen int64) (id string, err error)
	XGroupCreateMkStream(ctx context.Context, stream, group, start string) error
	// XReadGroup id 为 ">"(仅新消息)或 "0"/"0-0"(本 consumer 的 pending)。
	XReadGroup(ctx context.Context, stream, group, consumer string, count int64, block time.Duration, id string) ([]StreamMessage, error)
	// XReadGroupMulti 一次读取多个 stream;ids 与 streams 等长(多为 ">" 或 "0-0")。
	// block>0 且 ids 均为 ">" 时带 BLOCK。返回的 StreamMessage.Stream 为对应 stream key。
	XReadGroupMulti(ctx context.Context, streams []string, group, consumer string, count int64, block time.Duration, ids []string) ([]StreamMessage, error)
	// XAutoClaim 认领组内空闲过久的 pending(含其他 consumer)。
	XAutoClaim(ctx context.Context, stream, group, consumer string, minIdle time.Duration, start string, count int64) (nextStart string, msgs []StreamMessage, err error)
	// XPendingIDs 列出组内 pending 的消息 ID(最多 count 条)。
	XPendingIDs(ctx context.Context, stream, group string, count int64) (ids []string, err error)
	// XClaim 强制认领指定 pending(minIdle=0 表示立刻认领)。
	XClaim(ctx context.Context, stream, group, consumer string, minIdle time.Duration, ids ...string) ([]StreamMessage, error)
	XAck(ctx context.Context, stream, group string, ids ...string) error
}

Backend 底层流操作(由基础设施适配 Redis 等,本包不绑定具体驱动)。

type Def

type Def struct {
	Type   string // Envelope.Type / topic
	MaxLen int64  // Publish 时写入流的近似上限;0 跟随 Bus 默认
}

Def 业务事件目录项(名称与该 topic 留存策略,由业务包在常量旁声明)。

func (Def) Topic

func (d Def) Topic() string

Topic 默认与 Type 同名。

type Envelope

type Envelope struct {
	ID         string            // 后端生成的消息 ID(发布时可空)
	Type       string            // 事件类型(由业务约定)
	OccurredAt time.Time         // 业务发生时间
	Payload    []byte            // 业务载荷(通常 JSON)
	Headers    map[string]string // 可选扩展头
	MaxLen     int64             // 该次写入流近似上限;0 表示跟随 Bus 默认
}

Envelope 事件信封(传输层)。

type Handler

type Handler func(ctx context.Context, env Envelope) error

Handler 处理一条事件。 业务异常:日志用,return nil 或普通 error(框架 ACK)。 通信异常:return NoAck(err)(框架不 ACK)。

type NoAckError

type NoAckError struct {
	Err error
}

NoAckError 通信/基础设施失败:订阅方不得 ACK,保留 pending 以便重试。 与业务异常分离——业务异常只用于打印/写日志(return nil,或 return 普通 err 由框架打日志后 ACK)。

func (*NoAckError) Error

func (e *NoAckError) Error() string

func (*NoAckError) Unwrap

func (e *NoAckError) Unwrap() error

type NonIgnorableError deprecated

type NonIgnorableError = NoAckError

Deprecated: 使用 NoAckError。

type Publisher

type Publisher interface {
	Publish(ctx context.Context, topic string, env Envelope) error
}

Publisher 发布事件到 topic。

type StreamMessage

type StreamMessage struct {
	ID     string
	Stream string // 所属 stream key(多流读取时用于路由)
	Values map[string]string
}

StreamMessage Backend 读到的原始消息。

type Subscriber

type Subscriber interface {
	// Subscribe 阻塞直到 ctx 取消。group 区分监听者;consumer 为组内实例名。
	Subscribe(ctx context.Context, topic, group, consumer string, h Handler) error
}

Subscriber 以独立消费者组订阅 topic(同 topic 上每个 group 都会收到副本)。

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL