stream

package
v0.8.0 Latest Latest
Warning

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

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

Documentation

Overview

Package stream 提供流式扇出(广播)原语:把一个事件源 fan-out 给多个订阅者, 适合 SSE / WebSocket 等"一份数据推给 N 个连接"的场景。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Broadcaster

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

Broadcaster 把 Publish 的值广播给当前所有订阅者。 每个订阅者有独立的带缓冲队列;当某订阅者消费过慢、队列写满时, 按策略丢弃(默认丢最旧),保证慢订阅者不拖垮发布端与其它订阅者。

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

func New

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

New 创建一个 Broadcaster。

func (*Broadcaster[T]) Close

func (b *Broadcaster[T]) Close()

Close 关闭广播器:注销并关闭所有订阅者的 channel,之后 Publish 为 no-op、 Subscribe 返回已关闭的 channel。可重复调用。

func (*Broadcaster[T]) Publish

func (b *Broadcaster[T]) Publish(v T) int

Publish 把 v 广播给当前所有订阅者(非阻塞)。 某订阅者队列满时按 DropMode 丢弃,不会阻塞发布端。 返回成功投递(含因丢旧而入队)的订阅者数。

func (*Broadcaster[T]) Subscribe

func (b *Broadcaster[T]) Subscribe(ctx context.Context) (<-chan T, func())

Subscribe 注册一个订阅者,返回只读 channel 与取消函数。 取消函数(或 ctx 取消)会注销订阅并关闭返回的 channel。 Broadcaster 已 Close 时,返回一个已关闭的 channel 和空操作的取消函数。

func (*Broadcaster[T]) SubscriberCount

func (b *Broadcaster[T]) SubscriberCount() int

SubscriberCount 返回当前订阅者数量。

type DropMode

type DropMode int

DropMode 决定订阅者队列写满时的丢弃策略。

const (
	// DropOldest 丢弃队列中最旧的一条,写入新的(默认,适合"只关心最新"的推送)。
	DropOldest DropMode = iota
	// DropNewest 丢弃当前这条新值,保留队列已有内容。
	DropNewest
)

type Option

type Option func(*config)

Option 配置 Broadcaster。

func WithBufferSize

func WithBufferSize(n int) Option

WithBufferSize 设置每个订阅者的队列容量,默认 16。

func WithDropMode

func WithDropMode(m DropMode) Option

WithDropMode 设置队列写满时的丢弃策略,默认 DropOldest。

Jump to

Keyboard shortcuts

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