eventbus

package
v0.3.7 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2026 License: Apache-2.0 Imports: 2 Imported by: 0

Documentation

Overview

Package eventbus 提供进程内、按主题(topic)分发的泛型事件总线:发布者按 topic 发事件,订阅者按 topic 注册回调处理函数,解耦"谁发"与"谁收"。

与 pkg/stream 的区别(互补):

  • stream.Broadcaster 是单一数据源的 channel 扇出——所有订阅者收到同一份流, 订阅者用 range channel 消费,适合 SSE/WebSocket"一份数据推给 N 个连接";
  • eventbus 是多主题、回调式——订阅者只收自己关心的 topic,处理逻辑写在回调里, 适合"模块间事件解耦"(presence 上线事件 → 通知模块 + 审计模块各自订阅)。

泛型 T 为事件负载类型。分发模式:

  • 同步(默认):Publish 在调用方 goroutine 里依次执行所有 handler,返回即处理完;
  • 异步(WithAsync):每个 handler 在独立 goroutine 执行(pkg/safe 恢复 panic), Publish 不阻塞。同步模式下 handler 的 panic 也被恢复,不影响其它 handler。

并发安全。零值不可用,用 New 构造。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bus

type Bus[T any] struct {
	// contains filtered or unexported fields
}

Bus 按主题分发的事件总线。零值不可用,用 New 构造。并发安全。

func New

func New[T any](opts ...Option) *Bus[T]

New 创建事件总线。

func (*Bus[T]) Publish

func (b *Bus[T]) Publish(topic string, payload T) int

Publish 向 topic 发布一个事件,调用该 topic 下所有 handler。 返回被通知的 handler 数。同步模式下 Publish 返回时所有 handler 已执行完毕; 异步模式下仅表示已派发。

func (*Bus[T]) Subscribe

func (b *Bus[T]) Subscribe(topic string, handler Handler[T]) (unsubscribe func())

Subscribe 订阅 topic,返回退订函数。多次订阅同一 topic 各自独立、都会被调用。 调用退订函数后该 handler 不再收到事件(幂等)。

func (*Bus[T]) SubscriberCount

func (b *Bus[T]) SubscriberCount(topic string) int

SubscriberCount 返回某 topic 当前的订阅者数。

func (*Bus[T]) Topics

func (b *Bus[T]) Topics() []string

Topics 返回当前有订阅者的所有 topic(顺序不保证)。

type Handler

type Handler[T any] func(topic string, payload T)

Handler 事件处理回调。topic 为事件主题,payload 为负载。

type Option

type Option func(*config)

Option 配置 Bus。

func WithAsync

func WithAsync(async bool) Option

WithAsync 设置异步分发:每个 handler 在独立 goroutine 执行,Publish 不阻塞(默认同步)。

func WithOnPanic

func WithOnPanic(fn func(topic string, err error)) Option

WithOnPanic 设置 handler panic 时的回调(默认由 pkg/safe 静默恢复)。

Jump to

Keyboard shortcuts

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