throttle

package
v0.3.3 Latest Latest
Warning

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

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

Documentation

Overview

Package throttle 提供批量聚合触发原语:攒满 N 条或到达 T 时间即批量 flush。

典型场景:

  • 日志/事件批量写入(攒够 100 条或每秒 flush 一次)
  • 消息推送批量合并(减少网络往返)
  • 数据库批量 INSERT(攒 batch 提升吞吐)

与 chanx/stream 区别: throttle 是"攒批 + 定时触发"的专用原语, 不做扇出/路由/背压,只关注"何时 flush"。

纯标准库、并发安全。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FlushFunc

type FlushFunc[T any] func(items []T)

FlushFunc 批量处理回调。items 为攒满的一批数据。

type Option

type Option func(*config)

Option 配置 Throttle。

func WithInterval

func WithInterval(d time.Duration) Option

WithInterval 设置定时 flush 间隔(默认 1s)。到达间隔时间未满 batch 也 flush。

func WithMaxBatch

func WithMaxBatch(n int) Option

WithMaxBatch 设置触发 flush 的最大批量大小(默认 100)。

type Throttle

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

Throttle 批量聚合触发器。并发安全。 调用 Add 添加数据;数据攒满 maxBatch 或间隔到达时触发 flushFn。 需调用 Start 启动定时器,Stop 停止并 flush 剩余。

func New

func New[T any](flushFn FlushFunc[T], opts ...Option) *Throttle[T]

New 创建 Throttle。flushFn 在触发时被调用(可能来自 Add 的 goroutine 或定时器 goroutine)。

func (*Throttle[T]) Add

func (t *Throttle[T]) Add(item T)

Add 添加一条数据。如果攒满 maxBatch 则立即触发 flush。

func (*Throttle[T]) AddBatch

func (t *Throttle[T]) AddBatch(items []T)

AddBatch 添加多条数据。可能触发一次或多次 flush。

func (*Throttle[T]) Flush

func (t *Throttle[T]) Flush()

Flush 手动触发一次 flush(无论缓冲区是否达到阈值)。

func (*Throttle[T]) Len

func (t *Throttle[T]) Len() int

Len 返回当前缓冲区中的待 flush 数据量。

func (*Throttle[T]) Start

func (t *Throttle[T]) Start(ctx context.Context)

Start 启动定时 flush。必须调用一次;重复调用无效。

func (*Throttle[T]) Stop

func (t *Throttle[T]) Stop()

Stop 停止定时器并 flush 剩余数据。阻塞直到最后一次 flush 完成。

Jump to

Keyboard shortcuts

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