eventbus

package
v1.70.0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package eventbus 提供进程内事件总线(发布/订阅)。 支持同步与异步两种投递模式;异步模式下发布不阻塞调用方。 典型用途:业务模块解耦(订单创建后通知库存/通知/审计)、进程内观察者模式。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bus

type Bus struct {
	// contains filtered or unexported fields
}

Bus 是进程内事件总线。

func New

func New(async bool) *Bus

New 创建事件总线;async 为 true 时 Publish 异步投递(每个订阅者独立 goroutine)。

func (*Bus) Publish

func (b *Bus) Publish(ctx context.Context, event Event) error

Publish 发布事件。 同步模式:按订阅顺序执行,任一订阅者返回错误即停止并返回该错误。 异步模式:每个订阅者在独立 goroutine 中执行,错误仅记录到日志输出(不返回)。

func (*Bus) Subscribe

func (b *Bus) Subscribe(event string, handler Handler) func()

Subscribe 订阅指定事件;返回取消订阅函数(幂等)。

func (*Bus) SubscribeAll

func (b *Bus) SubscribeAll(handler Handler) func()

SubscribeAll 订阅全部事件(用于日志、审计等横切关注点)。

type Event

type Event struct {
	// Name 是事件名(如 order.created),订阅者按名称匹配。
	Name string
	// Data 是事件附带数据。
	Data interface{}
}

Event 是事件负载。

type Handler

type Handler func(ctx context.Context, event Event) error

Handler 是事件处理函数;返回错误会中止同事件后续订阅者(同步模式)。

type RedisBridge added in v1.66.0

type RedisBridge struct {
	// contains filtered or unexported fields
}

RedisBridge 通过 Redis Pub/Sub 桥接多个实例的进程内事件总线。 场景:多实例部署时,实例 A 发布的业务事件可被实例 B 的订阅者接收 (如分布式缓存失效通知、跨实例业务联动)。 注意:事件负载必须可 JSON 序列化;跨实例收到的 data 类型为 map[string]interface{}。

func NewRedisBridge added in v1.66.0

func NewRedisBridge(client *redis.Client, channel string, bus *Bus) *RedisBridge

NewRedisBridge 创建桥接器。 client 为 go-redis 客户端;channel 为 Redis 频道名(多环境隔离用不同频道); bus 为本地事件总线(同步/异步均可,桥接按本地语义投递)。

func (*RedisBridge) Publish added in v1.66.0

func (b *RedisBridge) Publish(ctx context.Context, event Event) error

Publish 把本地事件发布到 Redis 频道(其他实例的桥接器会转发到各自本地总线)。 本地订阅者如需同时收到事件,请额外调用 bus.Publish。

func (*RedisBridge) Start added in v1.66.0

func (b *RedisBridge) Start(ctx context.Context) error

Start 订阅 Redis 频道并把远端事件投递到本地总线,阻塞直到 ctx 取消。

Jump to

Keyboard shortcuts

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