Documentation
¶
Overview ¶
* @Author: kamalyes 501893067@qq.com * @Date: 2025-01-05 15:08:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-01-09 15:07:15 * @FilePath: \go-toolbox\pkg\syncx\atomic.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-01-05 15:27:15 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-01-05 15:27:15 * @FilePath: \go-toolbox\pkg\syncx\clone.go * @Description: 深拷贝工具 * * 三级性能优化: * 1. Cloner 接口 + Clone[T] 泛型函数 — 零反射,热路径类型实现接口即可 * 2. 预生成类型克隆闭包 — 首次遇某 struct 类型时生成专属 clone 函数, * 嵌套 struct 的 clone 函数递归预计算并捕获,热路径零缓存查找零 switch 分发 * 3. 反射通用兜底 — 未实现 Cloner 且无法预生成的类型走原始反射路径 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-01-23 09:08:56 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-01-23 09:22:55 * @FilePath: \go-toolbox\pkg\syncx\defer.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-01-23 09:08:56 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-23 19:35:00 * @FilePath: \go-toolbox\pkg\syncx\delay.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-03-04 12:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-03-04 12:00:00 * @FilePath: \go-toolbox\pkg\syncx\dynamic_ticker.go * @Description: 动态定时器,支持运行时调整频率,可与 EventLoop 配合使用 * * 使用说明: * * 1. 基础用法: * ticker := NewDynamicTicker(1 * time.Second) * ticker.Start() * defer ticker.Stop() * * for t := range ticker.C { * // 处理定时事件 * fmt.Println("tick at", t) * } * * 2. 动态调整频率: * ticker := NewDynamicTicker(1 * time.Second) * ticker.Start() * * // 运行时调整为 2 秒 * ticker.UpdateInterval(2 * time.Second) * * 3. 与 EventLoop 配合使用: * ticker := NewDynamicTicker(1 * time.Second) * ticker.Start() * defer ticker.Stop() * * NewEventLoop(ctx). * OnChannel(ticker.C, func(t time.Time) { * // 处理定时事件 * // 可以根据条件动态调整频率 * if needFaster { * ticker.UpdateInterval(500 * time.Millisecond) * } * }). * Run() * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-12-28 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-28 10:15:15 * @FilePath: \go-toolbox\pkg\syncx\event_loop.go * @Description: 事件循环执行器 - 处理多路复用的事件分发 * * 使用说明: * * 1. 基础事件循环: * loop := NewEventLoop(ctx) * loop.OnChannel(registerChan, handleRegister). * OnChannel(unregisterChan, handleUnregister). * OnTicker(5*time.Second, checkHeartbeat). * Run() * * 2. 完整示例: * loop := NewEventLoop(ctx). * OnChannel(h.register, h.handleRegister). * OnChannel(h.unregister, h.handleUnregister). * OnChannel(h.broadcast, h.handleBroadcast). * OnTicker(5*time.Second, h.checkHeartbeat). * OnTicker(10*time.Second, h.reportMetrics). * OnShutdown(h.cleanup). * Run() * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-12-13 13:05:03 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-08-13 17:50:20 * @FilePath: \go-toolbox\pkg\syncx\format.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-08-11 09:27:50 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-08-20 13:15:15 * @FilePath: \go-toolbox\pkg\syncx\func_chain.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-12-28 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-01-08 15:25:26 * @FilePath: \go-toolbox\pkg\syncx\go_executor.go * @Description: Goroutine 执行器 - 链式调用风格,集成 contextx * * 使用说明: * * 1. 基础 Goroutine 执行: * Go(). * OnPanic(func(r interface{}) { log.Error("panic", r) }). * Exec(func() { doSomething() }) * * 2. 带超时的 Context 执行: * Go(ctx). * WithTimeout(2 * time.Second). * OnError(func(err error) { log.Error(err) }). * OnPanic(func(r interface{}) { log.Error("panic", r) }). * ExecWithContext(func(ctx context.Context) error { * return repo.Save(ctx, data) * }) * * 3. 带延迟的执行: * Go(ctx). * WithDelay(5 * time.Second). * OnCancel(func() { log.Info("cancelled") }). * ExecWithContext(func(ctx context.Context) error { * return sendNotification(ctx) * }) * * 4. 完整示例: * Go(ctx). * WithTimeout(10 * time.Second). * WithDelay(1 * time.Second). * OnError(func(err error) { metrics.RecordError(err) }). * OnPanic(func(r interface{}) { sentry.CaptureException(r) }). * OnCancel(func() { log.Info("task cancelled") }). * ExecWithContext(func(ctx context.Context) error { * return processData(ctx) * }) * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-12-13 13:05:03 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-08-13 17:50:20 * @FilePath: \go-toolbox\pkg\syncx\lock.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-01-15 11:55:06 * @FilePath: \go-toolbox\pkg\syncx\map.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-06-11 13:15:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-06-17 10:19:57 * @FilePath: \go-toolbox\pkg\syncx\orderset.go * @Description: 泛型有序集合,支持所有可比较类型,保持元素插入顺序,支持高效查找和遍历 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-12-28 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-28 08:52:55 * @FilePath: \go-toolbox\pkg\syncx\parallel.go * @Description: 并发执行工具函数 * * 使用说明: * * 1. 回调风格 API (推荐): * - NewParallelExecutor: 创建 map 并发执行器,支持链式调用设置回调 * - NewParallelSliceExecutor: 创建 slice 并发执行器,支持链式调用设置回调 * * 可用回调: * OnSuccess(fn) - 每个任务成功时调用 * OnError(fn) - 每个任务失败时调用 * OnEachComplete(fn) - 每个任务完成时调用(无论成败) * OnComplete(fn) - 所有任务完成后调用,返回结果和错误集合 * * 示例: * NewParallelExecutor(clientMap). * OnSuccess(func(key, val, result) { log.Info("成功") }). * OnError(func(key, val, err) { log.Error("失败", err) }). * OnComplete(func(results, errors) { log.Info("全部完成") }). * Execute(func(key, val) (result, error) { return process(val) }) * * 2. 简化函数 (无返回值场景): * - ParallelForEach: 并发遍历 map,无返回值 * - ParallelForEachSlice: 并发遍历 slice,无返回值 * * 示例: * ParallelForEach(clientMap, func(key, client) { client.Close() }) * * 性能对比 (WaitGroup vs Channel): * - 小数据(3元素): WaitGroup 快 21%, 内存少 37.5% * - 中等数据(100元素): WaitGroup 快 25% * - 大数据(1000元素): 性能相近 * 结论: 优先使用 WaitGroup 实现 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-10-24 11:25:16 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-01-17 13:03:15 * @FilePath: \go-toolbox\pkg\syncx\pool.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-12-28 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-01-08 15:27:17 * @FilePath: \go-toolbox\pkg\syncx\recover.go * @Description: 统一的 panic 恢复处理 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-09 01:15:05 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-11 13:08:58 * @FilePath: \go-toolbox\pkg\syncx\set.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-06-05 16:25:18 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-08-11 11:17:19 * @FilePath: \go-toolbox\pkg\syncx\task.go * @Description: * 泛型参数说明: * * T - 任务输入类型 * - 定义:`T` 是一个类型参数,表示任务执行函数的输入类型 * - 用法:在任务函数中,`input` 参数的类型为 `T`, 这意味着你可以在创建任务时指定任何类型作为输入 * 例如,如果你创建一个任务来处理整数输入,则 `T` 可以是 `int`;如果任务需要处理字符串,则 `T` 可以是 `string` * * R - 任务结果类型 * - 定义:`R` 是一个类型参数,表示任务执行函数的返回结果类型 * - 用法:在任务函数中,返回值的类型为 `R`, 这使得你可以灵活地指定任务完成后返回的结果类型 * 例如,如果任务执行后需要返回一个字符串,则 `R` 可以是 `string`;如果返回一个整数,则 `R` 可以是 `int` * * U - 回调结果类型 * - 定义:`U` 是一个类型参数,表示任务成功或失败后的回调函数的返回结果类型 * - 用法:在设置成功或失败回调时,回调函数的返回值类型为 `U`, 这允许你指定回调函数的返回类型 * 例如,如果回调函数需要返回一个字符串,则 `U` 可以是 `string`;如果返回一个布尔值,则 `U` 可以是 `bool` * * 总结: * - `T`:表示任务输入的类型,允许灵活地定义任务需要处理的数据类型 * - `R`:表示任务执行的结果类型,使得任务的返回值可以是任何类型 * - `U`:表示回调函数的返回结果类型,允许在任务执行后处理结果并返回相应的数据类型 * * 通过使用这些泛型参数,`Task` 和 `TaskManager` 可以在不同的上下文中使用,适应不同类型的任务和回调,增强了代码的灵活性和可重用性 * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-08-20 09:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-08-20 09:00:00 * @FilePath: \go-toolbox\pkg\syncx\timewheel.go * @Description: * 分片时间轮(HashedWheelTimer)——16 分片 + 双向链表 bucket + 惰性取消, * O(1) 调度/取消/刷新,替代 O(N) 全量扫描,适用于百万级连接心跳超时管理 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-02-10 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-02-10 00:00:00 * @FilePath: \go-toolbox\pkg\syncx\worker_pool.go * @Description: Worker 池实现,用于限制并发 goroutine 数量,防止 OOM * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
Index ¶
- Variables
- func BuildContentExtra(data map[string]interface{}) string
- func Clone[T any](src *T) *T
- func CopyMeta(src, dst map[string]string)
- func DeepCopy(dst, src interface{}) error
- func FNVHashString32(s string) uint32
- func GetBoolFromData(data map[string]interface{}, key string) bool
- func GetInt64FromData(data map[string]interface{}, key string) int64
- func GetStringFromData(data map[string]interface{}, key string) string
- func KvHasher[K comparable]() func(K) uint32
- func MetaMapToString(meta map[string]string) string
- func MetaStringToMap(meta string) map[string]string
- func MustRecover(handler RecoverFunc)
- func NextPowerOfTwo(n int) int
- func ParallelForEach[K comparable, V any](m map[K]V, fn ParallelForEachFunc[K, V])
- func ParallelForEachSlice[T any](s []T, fn ParallelForEachSliceFunc[T])
- func ParseContentExtraToMap(data map[string]interface{}) map[string]string
- func Recover()
- func RecoverAndHandle(err *error, panicHandler RecoverFunc, errorHandler func(error))
- func RecoverToError(err *error, handler RecoverFunc)
- func RecoverWithHandler(handler RecoverFunc)
- func SafeGo(fn func(), onPanic RecoverFunc)
- func WithDefer(operation, df func())
- func WithDeferReturn[T any](operation func() (T, error), df func()) (T, error)
- func WithDeferReturnValue[T any](operation func() T, df func()) T
- func WithLock(lock Locker, operation func())
- func WithLockReturn[T any](lock Locker, operation func() (T, error)) (T, error)
- func WithLockReturnFunc[R any](lock Locker, operation func() R) R
- func WithLockReturnValue[T any](lock Locker, operation func() T) T
- func WithLockReturnWithE[T any, E any](lock Locker, operation func() (T, E)) (T, E)
- func WithRLock(lock RLocker, operation func())
- func WithRLockReturn[T any](lock RLocker, operation func() (T, error)) (T, error)
- func WithRLockReturnFunc[R any](lock RLocker, operation func() R) R
- func WithRLockReturnValue[T any](lock RLocker, operation func() T) T
- func WithRLockReturnWithE[T any, E any](lock RLocker, operation func() (T, E)) (T, E)
- func WithRUnlockThenLock(lock RLocker, operation func())
- func WithTryLock(lock TryLocker, operation func() error) error
- func WithTryLockReturn[T any](lock TryLocker, operation func() (T, error)) (T, error)
- func WithTryLockReturnValue[T any](lock TryLocker, operation func() T) (T, error)
- func WithTryLockReturnWithE[T any, E any](lock TryLocker, operation func() (T, E)) (T, E)
- func WithTryRLock(lock TryRLocker, operation func() error) error
- func WithTryRLockReturn[T any](lock TryRLocker, operation func() (T, error)) (T, error)
- func WithTryRLockReturnValue[T any](lock TryRLocker, operation func() T) (T, error)
- func WithTryRLockReturnWithE[T any, E any](lock TryRLocker, operation func() (T, E)) (T, E)
- func WithUnlockThenLock(lock Locker, operation func())
- type AtomicValue
- type BatchExecutor
- func (b *BatchExecutor) Context() context.Context
- func (b *BatchExecutor) ErrorCount() int
- func (b *BatchExecutor) Errors() map[int64]error
- func (b *BatchExecutor) Go(fn func() error)
- func (b *BatchExecutor) HasErrors() bool
- func (b *BatchExecutor) OnError(fn GoExecutorErrorHandler) *BatchExecutor
- func (b *BatchExecutor) OnPanic(fn GoExecutorPanicHandler) *BatchExecutor
- func (b *BatchExecutor) SetLimit(n int) *BatchExecutor
- func (b *BatchExecutor) SetMode(mode BatchExecutorMode) *BatchExecutor
- func (b *BatchExecutor) Wait() error
- type BatchExecutorMode
- type BatchProcessor
- type BatchProcessorOption
- type Bool
- type CallbackFunc
- type ChildRunner
- type Cloner
- type DelayFunc
- type DelayStrategy
- type Delayer
- func (d *Delayer[T]) Close()
- func (d *Delayer[T]) Execute() error
- func (d *Delayer[T]) GetLegacyResults() []*ExecutionResult
- func (d *Delayer[T]) GetResultChannel() <-chan T
- func (d *Delayer[T]) GetResults() []T
- func (d *Delayer[T]) GetStats() *ExecutionStats
- func (d *Delayer[T]) IsRunning() bool
- func (d *Delayer[T]) Stop()
- func (d *Delayer[T]) Wait() error
- func (d *Delayer[T]) WaitForCompletion()
- func (d *Delayer[T]) WithConcurrent(concurrent bool) *Delayer[T]
- func (d *Delayer[T]) WithContext(ctx context.Context) *Delayer[T]
- func (d *Delayer[T]) WithCustomDelay(delayFunc DelayFunc) *Delayer[T]
- func (d *Delayer[T]) WithDelay(delay time.Duration) *Delayer[T]
- func (d *Delayer[T]) WithDisableCallbacks(disable bool) *Delayer[T]
- func (d *Delayer[T]) WithFunction(f func() error) *Delayer[T]
- func (d *Delayer[T]) WithMaxConcurrency(maxConcurrency int) *Delayer[T]
- func (d *Delayer[T]) WithMaxDelay(maxDelay time.Duration) *Delayer[T]
- func (d *Delayer[T]) WithMultiplier(multiplier float64) *Delayer[T]
- func (d *Delayer[T]) WithOnAfterComplete(callback func(ctx *ExecutionContext)) *Delayer[T]
- func (d *Delayer[T]) WithOnBeforeStart(callback func(ctx *ExecutionContext)) *Delayer[T]
- func (d *Delayer[T]) WithOnComplete(callback func(result *ExecutionResult)) *Delayer[T]
- func (d *Delayer[T]) WithOnError(callback func(index int, err error) bool) *Delayer[T]
- func (d *Delayer[T]) WithOnErrorContext(callback ErrorHandlerFunc) *Delayer[T]
- func (d *Delayer[T]) WithOnProgress(callback TaskProgressFunc) *Delayer[T]
- func (d *Delayer[T]) WithOnStart(callback func(index int)) *Delayer[T]
- func (d *Delayer[T]) WithOnSuccess(callback CallbackFunc[T]) *Delayer[T]
- func (d *Delayer[T]) WithRandomBase(base float64) *Delayer[T]
- func (d *Delayer[T]) WithSimpleFunction(f func()) *Delayer[T]
- func (d *Delayer[T]) WithSimpleTaskFunc(taskFunc SimpleTaskFunc) *Delayer[T]
- func (d *Delayer[T]) WithStopOnError(stopOnError bool) *Delayer[T]
- func (d *Delayer[T]) WithStrategy(strategy DelayStrategy) *Delayer[T]
- func (d *Delayer[T]) WithTaskFunc(taskFunc TaskFunc[T]) *Delayer[T]
- func (d *Delayer[T]) WithTimes(count int) *Delayer[T]
- type DynamicTicker
- type ErrorHandlerFunc
- type EventLoop
- func (el *EventLoop) IfChannel(condition bool, ch interface{}, handler interface{}) *EventLoop
- func (el *EventLoop) IfTicker(condition bool, interval time.Duration, handler func()) *EventLoop
- func (el *EventLoop) OnChannel(ch interface{}, handler interface{}) *EventLoop
- func (el *EventLoop) OnPanic(fn func(interface{})) *EventLoop
- func (el *EventLoop) OnShutdown(fn func()) *EventLoop
- func (el *EventLoop) OnTicker(interval time.Duration, handler func()) *EventLoop
- func (el *EventLoop) Run()
- func (el *EventLoop) RunAsync()
- type ExecutionContext
- type ExecutionMode
- type ExecutionResult
- type ExecutionStats
- type FuncChain
- type FuncItem
- type GoExecutor
- func (g *GoExecutor) Exec(fn GoExecutorFunc)
- func (g *GoExecutor) ExecSubs()
- func (g *GoExecutor) ExecWithChildren(fn func(*ChildRunner))
- func (g *GoExecutor) ExecWithContext(fn GoExecutorContextFunc)
- func (g *GoExecutor) ExecWithResult(fn GoExecutorResultFunc) ...
- func (g *GoExecutor) OnCancel(fn GoExecutorCancelHandler) *GoExecutor
- func (g *GoExecutor) OnError(fn GoExecutorErrorHandler) *GoExecutor
- func (g *GoExecutor) OnPanic(fn GoExecutorPanicHandler) *GoExecutor
- func (g *GoExecutor) Sub(fn GoExecutorFunc) *GoExecutor
- func (g *GoExecutor) SubWithError(fn GoExecutorWaitFunc) *GoExecutor
- func (g *GoExecutor) Wait(fn GoExecutorWaitFunc) error
- func (g *GoExecutor) WithDelay(delay time.Duration) *GoExecutor
- func (g *GoExecutor) WithTimeout(timeout time.Duration) *GoExecutor
- func (g *GoExecutor) WithWaitGroup(wg *sync.WaitGroup) *GoExecutor
- type GoExecutorCancelHandler
- type GoExecutorContextFunc
- type GoExecutorErrorHandler
- type GoExecutorFunc
- type GoExecutorPanicHandler
- type GoExecutorResultFunc
- type GoExecutorWaitFunc
- type HashedWheelTimer
- func (t *HashedWheelTimer) Cancel(tt *TimerTask)
- func (t *HashedWheelTimer) CancelByKey(key string)
- func (t *HashedWheelTimer) Refresh(key string, delay time.Duration, task func()) *TimerTask
- func (t *HashedWheelTimer) Schedule(delay time.Duration, task func()) *TimerTask
- func (t *HashedWheelTimer) ScheduleWithKey(key string, delay time.Duration, task func()) *TimerTask
- func (t *HashedWheelTimer) Stats() TimerStats
- func (t *HashedWheelTimer) Stop()
- type Int32
- type Int64
- type LimitedPool
- type Lock
- type Locker
- type Map
- func (m *Map[K, V]) All(predicate func(K, V) bool) bool
- func (m *Map[K, V]) Any(predicate func(K, V) bool) bool
- func (m *Map[K, V]) Clear()
- func (m *Map[K, V]) Clone() *Map[K, V]
- func (m *Map[K, V]) CompareAndDelete(key K, value V) bool
- func (m *Map[K, V]) CompareAndSwap(key K, old, new V) bool
- func (m *Map[K, V]) Count(predicate func(K, V) bool) int
- func (m *Map[K, V]) Delete(key K)
- func (m *Map[K, V]) DeleteIf(predicate func(K, V) bool) int
- func (m *Map[K, V]) Equals(key K, value V, cmpFunc func(existing V) bool) bool
- func (m *Map[K, V]) Filter(predicate func(K, V) bool) []V
- func (m *Map[K, V]) FilterKeys(predicate func(K, V) bool) []K
- func (m *Map[K, V]) FilterMap(predicate func(K, V) bool) *Map[K, V]
- func (m *Map[K, V]) ForEach(fn func(K, V))
- func (m *Map[K, V]) GetOrCompute(key K, compute func() V) V
- func (m *Map[K, V]) GetOrStore(key K, defaultValue V) V
- func (m *Map[K, V]) IsEmpty() bool
- func (m *Map[K, V]) Keys() []K
- func (m *Map[K, V]) Load(key K) (V, bool)
- func (m *Map[K, V]) LoadAndDelete(key K) (V, bool)
- func (m *Map[K, V]) LoadOrStore(key K, new V) (V, bool)
- func (m *Map[K, V]) Range(run func(key K, value V) bool)
- func (m *Map[K, V]) Size() int
- func (m *Map[K, V]) Store(key K, value V)
- func (m *Map[K, V]) Swap(key K, value V) (pre V, ok bool)
- func (m *Map[K, V]) ToMap() map[K]V
- func (m *Map[K, V]) Update(key K, updater func(V) V) bool
- func (m *Map[K, V]) Values() []V
- type OrderedSet
- type ParallelCompleteCallback
- type ParallelEachCompleteCallback
- type ParallelErrorCallback
- type ParallelExecuteFunc
- type ParallelExecutor
- func (p *ParallelExecutor[K, V, R]) Execute(fn ParallelExecuteFunc[K, V, R])
- func (p *ParallelExecutor[K, V, R]) OnComplete(fn ParallelCompleteCallback[K, R]) *ParallelExecutor[K, V, R]
- func (p *ParallelExecutor[K, V, R]) OnEachComplete(fn ParallelEachCompleteCallback[K]) *ParallelExecutor[K, V, R]
- func (p *ParallelExecutor[K, V, R]) OnError(fn ParallelErrorCallback[K, V]) *ParallelExecutor[K, V, R]
- func (p *ParallelExecutor[K, V, R]) OnPanic(fn ParallelPanicCallback[K, V]) *ParallelExecutor[K, V, R]
- func (p *ParallelExecutor[K, V, R]) OnSuccess(fn ParallelSuccessCallback[K, V, R]) *ParallelExecutor[K, V, R]
- type ParallelForEachFunc
- type ParallelForEachSliceFunc
- type ParallelPanicCallback
- type ParallelSliceCompleteCallback
- type ParallelSliceEachCompleteCallback
- type ParallelSliceErrorCallback
- type ParallelSliceExecuteFunc
- type ParallelSliceExecutor
- func (p *ParallelSliceExecutor[T, R]) Execute(fn ParallelSliceExecuteFunc[T, R])
- func (p *ParallelSliceExecutor[T, R]) OnComplete(fn ParallelSliceCompleteCallback[R]) *ParallelSliceExecutor[T, R]
- func (p *ParallelSliceExecutor[T, R]) OnEachComplete(fn ParallelSliceEachCompleteCallback) *ParallelSliceExecutor[T, R]
- func (p *ParallelSliceExecutor[T, R]) OnError(fn ParallelSliceErrorCallback[T]) *ParallelSliceExecutor[T, R]
- func (p *ParallelSliceExecutor[T, R]) OnPanic(fn ParallelSlicePanicCallback[T]) *ParallelSliceExecutor[T, R]
- func (p *ParallelSliceExecutor[T, R]) OnSuccess(fn ParallelSliceSuccessCallback[T, R]) *ParallelSliceExecutor[T, R]
- func (p *ParallelSliceExecutor[T, R]) WithConcurrency(maxConcurrency int) *ParallelSliceExecutor[T, R]
- type ParallelSlicePanicCallback
- type ParallelSliceSuccessCallback
- type ParallelSuccessCallback
- type PeriodicTask
- func (t *PeriodicTask) GetExecuteFunc() func(ctx context.Context) error
- func (t *PeriodicTask) GetImmediateStart() bool
- func (t *PeriodicTask) GetInterval() time.Duration
- func (t *PeriodicTask) GetName() string
- func (t *PeriodicTask) GetOnError() func(name string, err error)
- func (t *PeriodicTask) GetOnOverlapSkipped() func(name string)
- func (t *PeriodicTask) GetOnStart() func(name string)
- func (t *PeriodicTask) GetOnStop() func(name string)
- func (t *PeriodicTask) GetPreventOverlap() bool
- func (t *PeriodicTask) IsExecuting() bool
- func (t *PeriodicTask) SetImmediateStart(immediateStart bool) *PeriodicTask
- func (t *PeriodicTask) SetOnError(onError func(name string, err error)) *PeriodicTask
- func (t *PeriodicTask) SetOnOverlapSkipped(onOverlapSkipped func(name string)) *PeriodicTask
- func (t *PeriodicTask) SetOnStart(onStart func(name string)) *PeriodicTask
- func (t *PeriodicTask) SetOnStop(onStop func(name string)) *PeriodicTask
- func (t *PeriodicTask) SetPreventOverlap(preventOverlap bool) *PeriodicTask
- type PeriodicTaskManager
- func (m *PeriodicTaskManager) AddSimpleTask(name string, interval time.Duration, ...) *PeriodicTaskManager
- func (m *PeriodicTaskManager) AddTask(task *PeriodicTask) *PeriodicTaskManager
- func (m *PeriodicTaskManager) AddTaskWithImmediateStart(name string, interval time.Duration, ...) *PeriodicTaskManager
- func (m *PeriodicTaskManager) AddTaskWithOverlapPrevention(name string, interval time.Duration, ...) *PeriodicTaskManager
- func (m *PeriodicTaskManager) AddTaskWithOverlapPreventionAndCallback(name string, interval time.Duration, ...) *PeriodicTaskManager
- func (m *PeriodicTaskManager) AddTaskWithOverlapPreventionImmediateAndCallback(name string, interval time.Duration, ...) *PeriodicTaskManager
- func (m *PeriodicTaskManager) ClearAllTasks()
- func (m *PeriodicTaskManager) GetTaskCount() int
- func (m *PeriodicTaskManager) GetTaskDetails(name ...string) []TaskDetailInfo
- func (m *PeriodicTaskManager) GetTaskNames() []string
- func (m *PeriodicTaskManager) IsRunning() bool
- func (m *PeriodicTaskManager) RemoveTask(name string) bool
- func (m *PeriodicTaskManager) RemoveTaskWithTimeout(name string, timeout time.Duration) bool
- func (m *PeriodicTaskManager) SetDefaultCallbacks(onStart func(name string), onStop func(name string)) *PeriodicTaskManager
- func (m *PeriodicTaskManager) SetDefaultErrorHandler(handler func(name string, err error)) *PeriodicTaskManager
- func (m *PeriodicTaskManager) Start() error
- func (m *PeriodicTaskManager) StartWithContext(ctx context.Context) error
- func (m *PeriodicTaskManager) Stop() error
- func (m *PeriodicTaskManager) StopWithTimeout(timeout time.Duration) error
- func (m *PeriodicTaskManager) Wait()
- func (m *PeriodicTaskManager) WaitForExecution(timeout time.Duration) error
- type Pool
- type PoolOption
- type RLocker
- type RWLock
- type RecoverFunc
- type ReturnFunc
- type Set
- func (s *Set[K]) Add(key K)
- func (s *Set[K]) AddAll(keys ...K)
- func (s *Set[K]) Clear()
- func (s *Set[K]) Delete(key K)
- func (s *Set[K]) DeleteAll(keys ...K)
- func (s *Set[K]) Elements() []K
- func (s *Set[K]) Has(key K) bool
- func (s *Set[K]) HasAll(keys ...K) (existing []K, all bool)
- func (s *Set[K]) IsEmpty() bool
- func (s *Set[K]) Size() int
- type ShardedMap
- func (m *ShardedMap[K, V]) Clear()
- func (m *ShardedMap[K, V]) ClearHalf()
- func (m *ShardedMap[K, V]) CompareAndDelete(key K, value V) bool
- func (m *ShardedMap[K, V]) CompareAndSwap(key K, old, new V) bool
- func (m *ShardedMap[K, V]) Count(filter func(K, V) bool) int
- func (m *ShardedMap[K, V]) Delete(key K)
- func (m *ShardedMap[K, V]) Has(key K) bool
- func (m *ShardedMap[K, V]) Keys() []K
- func (m *ShardedMap[K, V]) Len() int
- func (m *ShardedMap[K, V]) Load(key K) (V, bool)
- func (m *ShardedMap[K, V]) LoadAndDelete(key K) (V, bool)
- func (m *ShardedMap[K, V]) LoadOrStore(key K, value V) (V, bool)
- func (m *ShardedMap[K, V]) Range(fn func(key K, value V) bool)
- func (m *ShardedMap[K, V]) RangeParallel(workerNum int, fn func(key K, value V))
- func (m *ShardedMap[K, V]) Store(key K, value V)
- func (m *ShardedMap[K, V]) StoreBatch(items map[K]V)
- func (m *ShardedMap[K, V]) Swap(key K, value V) (V, bool)
- func (m *ShardedMap[K, V]) Values() []V
- func (m *ShardedMap[K, V]) WithShardLock(key K, fn func(shardData map[K]V))
- func (m *ShardedMap[K, V]) WithShardRLock(key K, fn func(shardData map[K]V))
- type ShardedMapOption
- type SimpleTaskFunc
- type StateMachine
- func (sm *StateMachine[S]) AllowTransition(from, to S)
- func (sm *StateMachine[S]) AllowTransitions(from S, toStates ...S)
- func (sm *StateMachine[S]) CanTransitionTo(to S) bool
- func (sm *StateMachine[S]) ClearCallbacks()
- func (sm *StateMachine[S]) ClearHistory()
- func (sm *StateMachine[S]) CurrentState() S
- func (sm *StateMachine[S]) DisallowTransition(from, to S)
- func (sm *StateMachine[S]) GetAllowedTransitions() []S
- func (sm *StateMachine[S]) GetHistory() []StateTransition[S]
- func (sm *StateMachine[S]) GetHistoryCount() int
- func (sm *StateMachine[S]) GetHistoryString() string
- func (sm *StateMachine[S]) GetLastTransition() (StateTransition[S], bool)
- func (sm *StateMachine[S]) GetLastTransitionDuration() time.Duration
- func (sm *StateMachine[S]) GetLastTransitionTime() time.Time
- func (sm *StateMachine[S]) GetRecentHistory(n int) []StateTransition[S]
- func (sm *StateMachine[S]) GetRecentHistoryString(n int) string
- func (sm *StateMachine[S]) GetTotalDuration() time.Duration
- func (sm *StateMachine[S]) IsTrackingHistory() bool
- func (sm *StateMachine[S]) MustTransitionTo(to S)
- func (sm *StateMachine[S]) OnEnter(state S, handler func(from S))
- func (sm *StateMachine[S]) OnExit(state S, handler func(to S))
- func (sm *StateMachine[S]) OnTransition(handler func(from, to S))
- func (sm *StateMachine[S]) Reset(initialState S)
- func (sm *StateMachine[S]) TransitionTo(to S) error
- type StateMachineOption
- type StateTransition
- type Task
- func (tk *Task[T, R, U]) AddDependency(dep *Task[T, R, U]) *Task[T, R, U]
- func (tk *Task[T, R, U]) GetCallbackDuration() time.Duration
- func (tk *Task[T, R, U]) GetCallbackError() error
- func (tk *Task[T, R, U]) GetCallbackResult() U
- func (tk *Task[T, R, U]) GetCallbackState() TaskState
- func (tk *Task[T, R, U]) GetDependExecutionMode() ExecutionMode
- func (tk *Task[T, R, U]) GetDependencyStates() map[string]TaskState
- func (tk *Task[T, R, U]) GetDepends() []*Task[T, R, U]
- func (tk *Task[T, R, U]) GetError() error
- func (tk *Task[T, R, U]) GetFnDuration() time.Duration
- func (tk *Task[T, R, U]) GetInput() T
- func (tk *Task[T, R, U]) GetMaxRetries() int32
- func (tk *Task[T, R, U]) GetName() string
- func (tk *Task[T, R, U]) GetResult() R
- func (tk *Task[T, R, U]) GetRetryCount() int32
- func (tk *Task[T, R, U]) GetState() TaskState
- func (tk *Task[T, R, U]) GetTaskHistory(taskName string) []TaskHistory
- func (tk *Task[T, R, U]) GetTaskType() TaskType
- func (tk *Task[T, R, U]) GetTimestamp() int64
- func (tk *Task[T, R, U]) GetTotalDuration() time.Duration
- func (tk *Task[T, R, U]) SetDependExecutionMode(executionMode ExecutionMode) *Task[T, R, U]
- func (tk *Task[T, R, U]) SetFailureCallback(callback TaskCallbackFunc[R, U]) *Task[T, R, U]
- func (tk *Task[T, R, U]) SetMaxHistorySize(maxHistorySize int) *Task[T, R, U]
- func (tk *Task[T, R, U]) SetMaxRetries(count int32) *Task[T, R, U]
- func (tk *Task[T, R, U]) SetPriority(priority int) *Task[T, R, U]
- func (tk *Task[T, R, U]) SetRetryInterval(retryInterval time.Duration) *Task[T, R, U]
- func (tk *Task[T, R, U]) SetSuccessCallback(callback TaskCallbackFunc[R, U]) *Task[T, R, U]
- func (tk *Task[T, R, U]) SetTimeout(timeout time.Duration) *Task[T, R, U]
- type TaskCallbackFunc
- type TaskDetailInfo
- type TaskExecuteFunc
- type TaskFunc
- type TaskHistory
- func (th *TaskHistory) GetCallbackDuration() time.Duration
- func (th *TaskHistory) GetError() error
- func (th *TaskHistory) GetFnDuration() time.Duration
- func (th *TaskHistory) GetResult() interface{}
- func (th *TaskHistory) GetState() TaskState
- func (th *TaskHistory) GetTaskType() TaskType
- func (th *TaskHistory) GetTimestamp() int64
- type TaskManager
- func (tm *TaskManager[T, R, U]) AddTask(task *Task[T, R, U]) *TaskManager[T, R, U]
- func (tm *TaskManager[T, R, U]) Cancel(taskName string)
- func (tm *TaskManager[T, R, U]) CancelAll()
- func (tm *TaskManager[T, R, U]) GetTask(name string) (*Task[T, R, U], bool)
- func (tm *TaskManager[T, R, U]) GetTasks() map[string]*Task[T, R, U]
- func (tm *TaskManager[T, R, U]) Run() error
- func (tm *TaskManager[T, R, U]) SetTrunDown(fn TaskTrunFunc[R]) *TaskManager[T, R, U]
- func (tm *TaskManager[T, R, U]) SetTrunUp(fn TaskTrunFunc[R]) *TaskManager[T, R, U]
- func (tm *TaskManager[T, R, U]) TrunDown() (result R, err error)
- func (tm *TaskManager[T, R, U]) TrunUp() (result R, err error)
- type TaskProgressFunc
- type TaskState
- type TaskTrunFunc
- type TaskType
- type Timer
- type TimerOption
- type TimerStats
- type TimerTask
- type TryLocker
- type TryRLocker
- type Uint32
- type Uint64
- type Uintptr
- type WorkerPool
- func (p *WorkerPool) Close() error
- func (p *WorkerPool) GetActiveWorkerCount() int
- func (p *WorkerPool) GetQueueSize() int
- func (p *WorkerPool) GetWorkerCount() int
- func (p *WorkerPool) IsClosed() bool
- func (p *WorkerPool) Submit(ctx context.Context, task WorkerTask) error
- func (p *WorkerPool) SubmitNonBlocking(task WorkerTask) error
- func (p *WorkerPool) Wait()
- type WorkerTask
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrClosed 表示 Worker 池已关闭 ErrClosed = errors.New("worker pool is closed") // ErrQueueFull 表示 Worker 池队列已满 ErrQueueFull = errors.New("worker pool queue is full") )
var ErrLockNotAcquired = errors.New("lock not acquired")
Functions ¶
func BuildContentExtra ¶
BuildContentExtra 构建额外内容JSON
func Clone ¶
func Clone[T any](src *T) *T
Clone 返回 src 的深拷贝 若 src 实现 Cloner 则零反射快速路径 推荐用法:msg := syncx.Clone(msg) 替代 syncx.DeepCopy(&dst, &src)
func DeepCopy ¶
func DeepCopy(dst, src interface{}) error
DeepCopy 复制源值到目标值
@params dst: 目标值的指针,必须是指向某种类型的指针 @params src: 源值的指针,必须是指向某种类型的指针
@return: 成功返回 nil;源为 nil 返回错误
func FNVHashString32 ¶
FNVHashString32 使用 FNV-1a 算法计算 string 的 32 位 hash 内联实现,零分配(对比 fnv.New32a()+Write 消除 heap alloc 和 []byte 转换)
func GetBoolFromData ¶
GetBoolFromData 从 Data map 中获取布尔值
func GetInt64FromData ¶
func GetStringFromData ¶
GetStringFromData 从 Data map 中获取字符串值
func KvHasher ¶
func KvHasher[K comparable]() func(K) uint32
KvHasher 为 ShardedMap 的 K 类型选择最优的 hash 函数 通过类型断言为常见 K 类型(string/整数族等)选择专用 hasher,避免反射开销
整数键必须经过位混合,不能直接把原值当 hash
分片下标取的是 hash 的低位(h & mask,mask = shardCount-1),而原值直接当 hash 意味着分片**完全由键的低位决定**真实的键常常在低位带结构:按分片数 对齐的 ID、乘过 1000 的编号、以分为单位的金额、毫秒时间戳 实测一万个键、64 个分片(混合前):
键步长 用到的分片 最大分片装入(理想 156) 1 64/64 157 8 8/64 1250 64 1/64 10000 ← 退化成一把全局锁 100 16/64 625 1000 8/64 1250
步长 64 时所有键挤进同一个分片,分片这件事等于没做,而且比普通 map 更糟—— 多付了分片的开销却只用到一把锁这类退化不会报错,只会在压测时表现为 「分片 map 没有想象中快」,极难归因,所以必须在 hasher 里挡住
[EN] Integer keys must be bit-mixed rather than used as their own hash. The shard index comes from the low bits of the hash (h & mask with mask = shardCount-1), so using the raw value means the shard is decided entirely by the key's low bits — and real keys often carry structure there: IDs aligned to the shard count, numbers multiplied by 1000, amounts in cents, millisecond timestamps. Measured over ten thousand keys across 64 shards before mixing, a stride of 64 put every key in one shard, degenerating to a single global lock while still paying for sharding. Such degradation raises no error; it merely shows up as "the sharded map is not as fast as expected", which is very hard to attribute, so the hasher has to prevent it
func MetaMapToString ¶
MetaMapToString 将 map 转换为 meta 字符串
func MetaStringToMap ¶
MetaStringToMap 将 meta 字符串转换为键值对的 map
func MustRecover ¶
func MustRecover(handler RecoverFunc)
MustRecover 必须恢复的 panic(会重新 panic)
示例:
defer MustRecover(func(r interface{}) {
log.Error("critical panic", r)
})
func ParallelForEach ¶
func ParallelForEach[K comparable, V any](m map[K]V, fn ParallelForEachFunc[K, V])
ParallelForEach 并发遍历 map 并对每个元素执行操作 使用 WaitGroup 确保所有 goroutine 完成后才返回
参数:
- m: 要遍历的 map
- fn: 对每个元素执行的函数
示例:
syncx.ParallelForEach(clientMap, func(key string, client *Client) {
client.Send(msg)
})
func ParallelForEachSlice ¶
func ParallelForEachSlice[T any](s []T, fn ParallelForEachSliceFunc[T])
ParallelForEachSlice 并发遍历 slice 并对每个元素执行操作 使用 WaitGroup 确保所有 goroutine 完成后才返回
参数:
- s: 要遍历的 slice
- fn: 对每个元素执行的函数
示例:
syncx.ParallelForEachSlice(clients, func(i int, client *Client) {
client.Send(msg)
})
func ParseContentExtraToMap ¶
ParseContentExtraToMap 将message.Data解析为map[string]string格式 用于protobuf的ContentExtra字段
func RecoverAndHandle ¶
func RecoverAndHandle(err *error, panicHandler RecoverFunc, errorHandler func(error))
RecoverAndHandle 恢复 panic 并在 defer 中处理错误 用于需要在同一个 defer 中完成 panic 恢复和错误处理的场景
示例:
func example() error {
var err error
defer RecoverAndHandle(&err,
func(r interface{}) { log.Error("panic", r) }, // panic handler
func(e error) { log.Error("error", e) }) // error handler
err = doSomething()
return err
}
func RecoverToError ¶
func RecoverToError(err *error, handler RecoverFunc)
RecoverToError 将 panic 转换为 error
示例:
func example() (err error) {
defer RecoverToError(&err, nil)
可能会 panic 的代码
return nil
}
func RecoverWithHandler ¶
func RecoverWithHandler(handler RecoverFunc)
RecoverWithHandler 使用自定义处理器恢复 panic
示例:
defer RecoverWithHandler(func(r interface{}) {
log.Error("panic", r)
})
func SafeGo ¶
func SafeGo(fn func(), onPanic RecoverFunc)
SafeGo 安全的 goroutine 启动,带 panic 恢复
示例:
SafeGo(func() {
// 可能会 panic 的代码
}, func(r interface{}) {
log.Error("panic recovered", r)
})
func WithDefer ¶
func WithDefer(operation, df func())
WithDefer 是一个通用的函数,用于在给定的操作上执行,并确保在操作完成后执行清理操作
func WithDeferReturn ¶
WithDeferReturn 是一个通用的函数,用于在给定的操作上执行,并确保在操作完成后执行清理操作 该函数支持返回值和错误处理
func WithDeferReturnValue ¶
func WithDeferReturnValue[T any](operation func() T, df func()) T
WithDeferReturnValue 是一个通用的函数,用于在给定的操作上执行,并确保在操作完成后执行清理操作 该函数支持返回值
func WithLockReturn ¶
WithLockReturn 是一个支持返回值的函数,用于在给定的锁上执行操作
func WithLockReturnFunc ¶
WithLockReturnFunc 是一个通用函数,支持任意返回值的函数(写锁版本)
func WithLockReturnValue ¶
WithLockReturnValue 是一个支持返回值的函数,用于在给定的锁上执行操作,不返回错误
func WithLockReturnWithE ¶
WithLockReturnWithE 是一个支持返回值和自定义泛型的函数,用于在给定的锁上执行操作
func WithRLockReturn ¶
WithRLockReturn 是一个支持返回值的函数,用于在给定的读锁上执行操作
func WithRLockReturnFunc ¶
WithRLockReturnFunc 是一个通用函数,支持任意返回值的函数 使用示例:
result := syncx.WithRLockReturnFunc(&mu, func() interface{} {
return []interface{}{val1, val2, val3}
})
values := result.([]interface{})
val1, val2, val3 := values[0], values[1], values[2]
func WithRLockReturnValue ¶
WithRLockReturnValue 是一个支持返回值的函数,用于在给定的读锁上执行操作,不返回错误
func WithRLockReturnWithE ¶
WithRLockReturnWithE 是一个支持返回值和自定义泛型的函数,用于在给定的读锁上执行操作
func WithRUnlockThenLock ¶
func WithRUnlockThenLock(lock RLocker, operation func())
WithRUnlockThenLock 是一个高阶函数,用于在给定的锁上先解锁,然后执行指定的操作,最后重新上锁 注意:在调用此函数之前,确保锁已被锁定 该函数适用于需要在执行操作之前释放锁的场景,例如在进行某些需要不被锁定的操作时 通过将操作封装在函数中,允许灵活地控制锁的使用
func WithTryLock ¶
WithTryLock 在支持 TryLock 的锁上尝试执行操作,成功获取锁才执行
func WithTryLockReturn ¶
WithTryLockReturn 在支持 TryLock 的锁上尝试执行操作,成功获取锁才执行,支持返回值和错误
func WithTryLockReturnValue ¶
WithTryLockReturnValue 在支持 TryLock 的锁上尝试执行操作,成功获取锁才执行,支持返回值,不返回错误
func WithTryLockReturnWithE ¶
WithTryLockReturnWithE 在支持 TryLock 的锁上尝试执行操作,成功获取锁才执行,支持返回值和错误
func WithTryRLock ¶
func WithTryRLock(lock TryRLocker, operation func() error) error
WithTryRLock 在支持 TryRLock 的读锁上尝试执行操作,成功获取读锁才执行
func WithTryRLockReturn ¶
func WithTryRLockReturn[T any](lock TryRLocker, operation func() (T, error)) (T, error)
WithTryRLockReturn 在支持 TryRLock 的读锁上尝试执行操作,成功获取读锁才执行,支持返回值和错误
func WithTryRLockReturnValue ¶
func WithTryRLockReturnValue[T any](lock TryRLocker, operation func() T) (T, error)
WithTryRLockReturnValue 在支持 TryRLock 的读锁上尝试执行操作,成功获取读锁才执行,支持返回值,不返回错误
func WithTryRLockReturnWithE ¶
func WithTryRLockReturnWithE[T any, E any](lock TryRLocker, operation func() (T, E)) (T, E)
WithTryRLockReturnWithE 在支持 TryRLock 的读锁上尝试执行操作,成功获取读锁才执行,支持返回值和错误
func WithUnlockThenLock ¶
func WithUnlockThenLock(lock Locker, operation func())
WithUnlockThenLock 是一个高阶函数,用于在给定的锁上先解锁,然后执行指定的操作,最后重新上锁 注意:在调用此函数之前,确保锁已被锁定 该函数适用于需要在执行操作之前释放锁的场景,例如在进行某些需要不被锁定的操作时 通过将操作封装在函数中,允许灵活地控制锁的使用
Types ¶
type AtomicValue ¶
type AtomicValue[T any] struct { // contains filtered or unexported fields }
AtomicValue 泛型原子值包装器
func NewAtomicValue ¶
func NewAtomicValue[T any](val T) *AtomicValue[T]
NewAtomicValue 创建一个新的 AtomicValue 实例
func (*AtomicValue[T]) CompareAndSwap ¶
func (av *AtomicValue[T]) CompareAndSwap(old, new T) bool
CompareAndSwap 原子地比较并交换值
type BatchExecutor ¶
type BatchExecutor struct {
// contains filtered or unexported fields
}
BatchExecutor 批量并发执行器,支持并发限制和两种错误处理模式 所有方法都是并发安全的
func NewBatchExecutor ¶
func NewBatchExecutor(ctx context.Context) *BatchExecutor
NewBatchExecutor 创建批量并发执行器(默认快速失败模式)
示例:
exec := NewBatchExecutor(ctx).
SetLimit(10).
SetMode(ContinueOnErrorMode). // 可选:设置继续执行模式
OnPanic(func(r interface{}) { log.Error("panic", r) }).
OnError(func(err error) { log.Error(err) })
for _, item := range items {
exec.Go(func() error {
return processItem(item)
})
}
err := exec.Wait() // 快速失败模式返回第一个错误
errors := exec.Errors() // 获取所有错误映射
func (*BatchExecutor) Context ¶
func (b *BatchExecutor) Context() context.Context
Context 返回执行器的 context
func (*BatchExecutor) Errors ¶
func (b *BatchExecutor) Errors() map[int64]error
Errors 获取所有错误映射(并发安全) 返回 map[taskID]error,其中 taskID 是任务提交的顺序编号(从1开始)
func (*BatchExecutor) OnError ¶
func (b *BatchExecutor) OnError(fn GoExecutorErrorHandler) *BatchExecutor
OnError 设置错误处理器(每个错误都会调用)
func (*BatchExecutor) OnPanic ¶
func (b *BatchExecutor) OnPanic(fn GoExecutorPanicHandler) *BatchExecutor
OnPanic 设置 panic 处理器
func (*BatchExecutor) SetLimit ¶
func (b *BatchExecutor) SetLimit(n int) *BatchExecutor
SetLimit 设置最大并发数
func (*BatchExecutor) SetMode ¶
func (b *BatchExecutor) SetMode(mode BatchExecutorMode) *BatchExecutor
SetMode 设置执行模式
type BatchExecutorMode ¶
type BatchExecutorMode int
BatchExecutorMode 批量执行器模式
const ( // FailFastMode 快速失败模式:遇到第一个错误立即停止提交新任务 FailFastMode BatchExecutorMode = iota // ContinueOnErrorMode 继续执行模式:即使有错误也继续执行所有任务 ContinueOnErrorMode )
type BatchProcessor ¶
type BatchProcessor[T any] struct { // contains filtered or unexported fields }
BatchProcessor 泛型批量处理器 持续收集 T 类型的请求,满 batchSize 或每 flushInterval 触发一次 flush
func NewBatchProcessor ¶
func NewBatchProcessor[T any](queueSize, batchSize int, flushInterval time.Duration, flushFn func(batch []T), opts ...BatchProcessorOption[T]) *BatchProcessor[T]
NewBatchProcessor 创建批量处理器并启动后台 worker
参数:
- queueSize: channel 缓冲大小(建议 4096)
- batchSize: 每批最大数量(建议 100)
- flushInterval: 最大 flush 间隔(建议 500ms)
- flushFn: flush 回调,接收一批数据
- opts: 可选配置(WithClone / WithPanicHandler / WithName)
向后兼容:opts 为空时行为与旧版完全一致
func (*BatchProcessor[T]) DroppedCount ¶
func (p *BatchProcessor[T]) DroppedCount() int64
DroppedCount 返回累计丢弃的条目数(队列满时丢弃) 用于监控背压情况,判断是否需要扩容 queueSize 或优化 flush 性能
func (*BatchProcessor[T]) Name ¶
func (p *BatchProcessor[T]) Name() string
Name 返回处理器名称(通过 WithName 设置)
func (*BatchProcessor[T]) Submit ¶
func (p *BatchProcessor[T]) Submit(item T) bool
Submit 非阻塞提交一条数据
行为说明:
- 队列未满:item 写入 channel,返回 true
- 队列已满:不会阻塞等待,也不会重试,直接走 default 分支丢弃该 item,返回 false
- 若设置了 WithClone,Submit 时会先克隆 item(数据隔离)
也就是说队列满之后,新提交的数据进不来,会被静默丢弃(最终一致性语义) 调用方可根据返回值决定后续处理:
- 记录 metric(如 DroppedCount)便于监控背压
- 降级处理(如改走同步更新、写本地缓冲等)
这种"非阻塞 + 丢弃"策略适用于可丢失的非核心路径(如消息状态更新), 避免生产者因队列满而阻塞,拖垮上游主流程
func (*BatchProcessor[T]) SubmitBlocking ¶
func (p *BatchProcessor[T]) SubmitBlocking(ctx context.Context, item T) bool
SubmitBlocking 阻塞式提交一条数据(不丢数据的兜底方案)
行为说明:
- 队列未满:item 立即写入 channel,返回 true
- 队列已满:阻塞等待,直到有空位可写入(返回 true)或 ctx 被取消/超时(返回 false)
- 若设置了 WithClone,Submit 时会先克隆 item(数据隔离)
与 Submit 的区别:
- Submit:队列满立即丢弃,适合可丢失的非核心路径(如消息状态更新)
- SubmitBlocking:队列满时背压传导给调用方,适合不能丢数据的核心路径(如订单、扣款)
注意事项:
- 阻塞期间会占用调用 goroutine,建议配合 ctx 超时使用,避免长时间卡住
- 若下游 flush 持续慢导致队列长期满,阻塞会向上游传导背压,上游需有相应限流/超时机制
- ctx.Done() 触发时该条数据被丢弃(由调用方决定是否重试/落盘补偿)
兜底策略选择:
- 不想丢 + 可接受短暂阻塞 → SubmitBlocking(ctx, item)
- 不想阻塞 + 可接受丢失 → Submit(item)
- 想要"先阻塞再降级" → SubmitBlocking 配合较短 ctx 超时,超时后走降级逻辑
type BatchProcessorOption ¶
type BatchProcessorOption[T any] func(*BatchProcessor[T])
BatchProcessorOption 批量处理器配置选项(函数式选项模式)
func WithBatchProcessorClone ¶
func WithBatchProcessorClone[T any](fn func(T) T) BatchProcessorOption[T]
WithBatchProcessorClone 设置克隆函数,Submit 时对 item 执行 Clone 防止调用方在 Submit 后修改 item 影响异步 flush(数据隔离) 适用于 item 包含指针/切片/Map 等引用类型的场景
func WithBatchProcessorName ¶
func WithBatchProcessorName[T any](name string) BatchProcessorOption[T]
WithBatchProcessorName 设置处理器名称,用于日志和监控标识
func WithBatchProcessorPanicHandler ¶
func WithBatchProcessorPanicHandler[T any](handler RecoverFunc) BatchProcessorOption[T]
WithBatchProcessorPanicHandler 设置 flush panic 处理器 flush 发生 panic 时调用 handler 恢复,单次 flush 失败不崩溃 worker(容错) 不设置时静默恢复(recover),避免 worker 退出
type Bool ¶
type Bool struct {
// contains filtered or unexported fields
}
Bool 类型,使用 atomic.Int32 来表示布尔值
type CallbackFunc ¶
type CallbackFunc[T any] func(ctx *ExecutionContext, result T)
CallbackFunc 泛型回调函数类型
type ChildRunner ¶
type ChildRunner struct {
// contains filtered or unexported fields
}
ChildRunner 子任务运行器,用于在父 goroutine 中启动子 goroutine
func (*ChildRunner) Go ¶
func (c *ChildRunner) Go(fn GoExecutorFunc) *ChildRunner
Go 启动一个子 goroutine
func (*ChildRunner) GoWithError ¶
func (c *ChildRunner) GoWithError(fn GoExecutorWaitFunc) *ChildRunner
GoWithError 启动一个带错误返回的子 goroutine
type DelayStrategy ¶
type DelayStrategy int
DelayStrategy 定义延迟策略
const ( // FixedDelayStrategy 固定延迟策略 FixedDelayStrategy DelayStrategy = iota // LinearDelayStrategy 线性递增延迟策略 LinearDelayStrategy // ExponentialDelayStrategy 指数延迟策略 ExponentialDelayStrategy // RandomDelayStrategy 随机延迟策略 RandomDelayStrategy // CustomDelayStrategy 自定义延迟策略 CustomDelayStrategy )
type Delayer ¶
type Delayer[T any] struct { // contains filtered or unexported fields }
Delayer 统一的泛型延迟执行器
func (*Delayer[T]) GetLegacyResults ¶
func (d *Delayer[T]) GetLegacyResults() []*ExecutionResult
GetLegacyResults 获取所有执行结果(向后兼容)
func (*Delayer[T]) GetResultChannel ¶
func (d *Delayer[T]) GetResultChannel() <-chan T
GetResultChannel 获取结果通道(只读)
func (*Delayer[T]) WaitForCompletion ¶
func (d *Delayer[T]) WaitForCompletion()
WaitForCompletion 等待任务完成
func (*Delayer[T]) WithConcurrent ¶
WithConcurrent 设置是否并发执行
func (*Delayer[T]) WithContext ¶
WithContext 设置上下文
func (*Delayer[T]) WithCustomDelay ¶
WithCustomDelay 设置自定义延迟函数
func (*Delayer[T]) WithDisableCallbacks ¶
WithDisableCallbacks 设置是否禁用回调以提升性能
func (*Delayer[T]) WithFunction ¶
WithFunction 设置要执行的函数
func (*Delayer[T]) WithMaxConcurrency ¶
WithMaxConcurrency 设置最大并发数
func (*Delayer[T]) WithMaxDelay ¶
WithMaxDelay 设置最大延迟时间
func (*Delayer[T]) WithMultiplier ¶
WithMultiplier 设置指数策略的倍数
func (*Delayer[T]) WithOnAfterComplete ¶
func (d *Delayer[T]) WithOnAfterComplete(callback func(ctx *ExecutionContext)) *Delayer[T]
WithOnAfterComplete 设置完成执行后回调
func (*Delayer[T]) WithOnBeforeStart ¶
func (d *Delayer[T]) WithOnBeforeStart(callback func(ctx *ExecutionContext)) *Delayer[T]
WithOnBeforeStart 设置开始执行前回调
func (*Delayer[T]) WithOnComplete ¶
func (d *Delayer[T]) WithOnComplete(callback func(result *ExecutionResult)) *Delayer[T]
WithOnComplete 设置完成执行回调(向后兼容)
func (*Delayer[T]) WithOnError ¶
WithOnError 设置错误处理回调(向后兼容)
func (*Delayer[T]) WithOnErrorContext ¶
func (d *Delayer[T]) WithOnErrorContext(callback ErrorHandlerFunc) *Delayer[T]
WithOnErrorContext 设置错误处理回调
func (*Delayer[T]) WithOnProgress ¶
func (d *Delayer[T]) WithOnProgress(callback TaskProgressFunc) *Delayer[T]
WithOnProgress 设置进度回调
func (*Delayer[T]) WithOnStart ¶
WithOnStart 设置开始执行回调(向后兼容)
func (*Delayer[T]) WithOnSuccess ¶
func (d *Delayer[T]) WithOnSuccess(callback CallbackFunc[T]) *Delayer[T]
WithOnSuccess 设置成功回调
func (*Delayer[T]) WithRandomBase ¶
WithRandomBase 设置随机基数(用于随机延迟策略)
func (*Delayer[T]) WithSimpleFunction ¶
WithSimpleFunction 设置无返回值的函数
func (*Delayer[T]) WithSimpleTaskFunc ¶
func (d *Delayer[T]) WithSimpleTaskFunc(taskFunc SimpleTaskFunc) *Delayer[T]
WithSimpleTaskFunc 设置简单任务函数(无返回值)
func (*Delayer[T]) WithStopOnError ¶
WithStopOnError 设置遇到错误是否停止
func (*Delayer[T]) WithStrategy ¶
func (d *Delayer[T]) WithStrategy(strategy DelayStrategy) *Delayer[T]
WithStrategy 设置延迟策略
func (*Delayer[T]) WithTaskFunc ¶
WithTaskFunc 设置泛型任务函数
type DynamicTicker ¶
type DynamicTicker struct {
C chan time.Time // 对外暴露的通道,接收定时事件
// contains filtered or unexported fields
}
DynamicTicker 动态定时器,支持运行时调整频率
特性:
- 支持运行时动态调整定时器间隔
- 线程安全,可在多个 goroutine 中调用
- 非阻塞发送,不会因为接收方慢而阻塞定时器
- 可与 EventLoop 无缝集成
注意事项:
- 必须调用 Start() 才能开始工作
- 使用完毕后应调用 Stop() 释放资源
- C 通道有 1 个缓冲,如果接收方处理慢会丢弃部分 tick
func NewDynamicTicker ¶
func NewDynamicTicker(interval time.Duration) *DynamicTicker
NewDynamicTicker 创建动态定时器 注意:
- 创建后需要调用 Start() 才能开始工作
- 定时器不会自动启动
func (*DynamicTicker) GetInterval ¶
func (dt *DynamicTicker) GetInterval() time.Duration
GetInterval 获取当前间隔
func (*DynamicTicker) Start ¶
func (dt *DynamicTicker) Start()
Start 启动定时器
功能:
- 创建底层 time.Ticker 并启动后台 goroutine
- 如果已经启动,重复调用不会有任何效果
注意:
- 线程安全,可以在多个 goroutine 中调用
- 启动后会立即开始按照 interval 发送 tick 事件
func (*DynamicTicker) UpdateInterval ¶
func (dt *DynamicTicker) UpdateInterval(interval time.Duration)
UpdateInterval 动态更新定时器间隔 功能:
- 如果新间隔与当前间隔相同,不做任何操作
- 如果定时器正在运行,会立即应用新的间隔
- 使用 ticker.Reset() 实现无缝切换,不会丢失正在进行的 tick
注意:
- 线程安全,可以在任何时候调用
- 可以在定时器启动前或运行中调用
type ErrorHandlerFunc ¶
type ErrorHandlerFunc func(ctx *ExecutionContext) (shouldContinue bool)
ErrorHandlerFunc 错误处理回调函数类型
type EventLoop ¶
type EventLoop struct {
// contains filtered or unexported fields
}
EventLoop 事件循环执行器 用于统一管理多个通道和定时器的事件分发,替代复杂的 select 循环
主要功能:
- 通道事件处理: 监听多个通道,自动分发到对应的处理函数
- 定时器管理: 支持多个定时器,自动管理生命周期
- Panic 恢复: 自动捕获处理函数中的 panic
- 优雅关闭: 支持 context 取消和资源清理
使用场景:
- WebSocket/SSE 服务端的事件循环
- 消息队列消费者
- 任何需要监听多个事件源的场景
Example ¶
Example 示例
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
registerCh := make(chan string, 10)
unregisterCh := make(chan string, 10)
loop := NewEventLoop(ctx).
OnChannel(registerCh, func(id string) {
// 处理注册
}).
OnChannel(unregisterCh, func(id string) {
// 处理注销
}).
OnTicker(5*time.Second, func() {
// 定期心跳检查
}).
OnShutdown(func() {
// 清理资源
})
// 运行事件循环
go loop.Run()
// 或者异步运行
// loop.RunAsync()
func NewEventLoop ¶
NewEventLoop 创建新的事件循环 参数 ctx 用于控制事件循环的生命周期,当 ctx 被取消时,事件循环会自动退出
示例:
ctx, cancel := context.WithCancel(context.Background()) loop := NewEventLoop(ctx) // ... 配置事件处理器 ... go loop.Run() // 需要停止时 cancel()
func (*EventLoop) IfChannel ¶
IfChannel 条件注册通道事件处理器 只有当条件为 true 时才注册通道监听
参数:
- condition: 条件判断,为 true 时才注册
- ch: 必须是一个通道类型
- handler: 必须是一个函数,接受通道元素类型的参数
示例:
// 只有当启用某功能时才监听该通道
loop.IfChannel(config.EnableFeature, featureChan, func(msg Message) {
handleFeature(msg)
})
func (*EventLoop) IfTicker ¶
IfTicker 条件注册定时器事件处理器 只有当条件为 true 时才注册定时器
参数:
- condition: 条件判断,为 true 时才注册
- interval: 定时间隔(如 5*time.Second, 1*time.Minute)
- handler: 定时触发时执行的函数,无参数无返回值
示例:
// 只有当启用清理时才注册定时器
loop.IfTicker(config.EnableCleanup, 30*time.Minute, func() {
cleanupExpiredData()
})
func (*EventLoop) OnChannel ¶
OnChannel 注册通道事件处理器 当通道接收到数据时,会调用对应的处理函数
参数:
- ch: 必须是一个通道类型(如 chan int, chan string, chan *Client 等)
- handler: 必须是一个函数,接受通道元素类型的参数
类型检查:
- 会在运行时通过反射验证 ch 是否为通道类型
- 会验证 handler 的参数类型是否匹配通道元素类型
示例:
registerChan := make(chan *Client, 100)
loop.OnChannel(registerChan, func(client *Client) {
handleRegister(client)
})
messageChan := make(chan Message, 100)
loop.OnChannel(messageChan, func(msg Message) {
handleMessage(msg)
})
func (*EventLoop) OnPanic ¶
OnPanic 设置 panic 处理器 当事件处理函数中发生 panic 时,会调用此函数
特性:
- 捕获所有处理函数中的 panic,防止整个事件循环崩溃
- panic 发生后,事件循环会继续运行,处理其他事件
- 如果设置了多次,只有最后一次设置的函数会生效
用途:
- 记录 panic 日志
- 上报错误到监控系统
- 发送告警通知
示例:
loop.OnPanic(func(r interface{}) {
log.Error("事件处理panic", "panic", r, "stack", string(debug.Stack()))
sentry.CaptureException(fmt.Errorf("panic: %v", r))
})
func (*EventLoop) OnShutdown ¶
OnShutdown 设置关闭时的回调 当事件循环退出时(context 取消或发生 panic),会调用此函数进行清理
用途:
- 关闭数据库连接
- 清理临时文件
- 保存状态数据
- 记录关闭日志
注意:
- 此函数会在 defer 中执行,保证一定会被调用
- 如果设置了多次,只有最后一次设置的函数会生效
示例:
loop.OnShutdown(func() {
log.Info("事件循环已停止")
db.Close()
saveState()
})
func (*EventLoop) OnTicker ¶
OnTicker 注册定时器事件处理器 按指定的时间间隔周期性地执行处理函数
参数:
- interval: 定时间隔(如 5*time.Second, 1*time.Minute)
- handler: 定时触发时执行的函数,无参数无返回值
特性:
- 定时器会在 Run() 方法中自动创建
- 定时器会在事件循环结束时自动停止
- 支持注册多个定时器,它们互不干扰
示例:
// 每5秒检查一次心跳
loop.OnTicker(5*time.Second, func() {
checkHeartbeat()
})
// 每1分钟清理一次过期数据
loop.OnTicker(1*time.Minute, func() {
cleanupExpiredData()
})
func (*EventLoop) Run ¶
func (el *EventLoop) Run()
Run 运行事件循环(阻塞) 开始监听所有注册的事件源,直到 context 被取消
执行流程:
- 构建 select cases(包括通道、定时器)
- 启动所有定时器
- 进入 select 循环,等待事件
- 接收到事件时,调用对应的处理函数
- context 取消时退出循环
- 停止所有定时器,调用 OnShutdown 回调
错误处理:
- 自动捕获所有处理函数中的 panic
- panic 不会导致事件循环崩溃
- 通过 OnPanic 回调通知上层
示例:
loop := NewEventLoop(ctx).
OnChannel(ch1, handler1).
OnChannel(ch2, handler2).
OnTicker(5*time.Second, tickHandler)
// 阻塞运行,直到 context 被取消
loop.Run()
func (*EventLoop) RunAsync ¶
func (el *EventLoop) RunAsync()
RunAsync 异步运行事件循环(非阻塞) 在新的 goroutine 中运行事件循环,立即返回
与 Run 的区别:
- Run: 阻塞当前 goroutine,直到 context 被取消
- RunAsync: 在新 goroutine 中运行,立即返回
使用场景:
- 需要在主 goroutine 中继续执行其他任务
- 需要同时运行多个事件循环
示例:
loop := NewEventLoop(ctx).
OnChannel(ch, handler).
OnTicker(5*time.Second, tickHandler)
// 异步运行,不阻塞
loop.RunAsync()
// 可以继续执行其他代码
doOtherWork()
type ExecutionContext ¶
type ExecutionContext struct {
Index int // 执行索引
Attempt int // 尝试次数(从0开始)
StartTime time.Time // 开始时间
EndTime time.Time // 结束时间
Duration time.Duration // 执行耗时
Error error // 执行错误
Skipped bool // 是否被跳过
Delay time.Duration // 实际延迟时间
Strategy DelayStrategy // 使用的延迟策略
Concurrent bool // 是否并发执行
Cancelled bool // 是否被取消
Retryable bool // 是否可重试
Metadata map[string]interface{} // 自定义元数据
}
ExecutionContext 执行上下文,包含执行过程中的全部信息
type ExecutionMode ¶
type ExecutionMode int
ExecutionMode 表示任务执行模式
const ( Sequential ExecutionMode = iota // 顺序执行 Concurrent // 并发执行 )
type ExecutionResult ¶
type ExecutionResult struct {
Index int // 执行索引
StartTime time.Time // 开始时间
EndTime time.Time // 结束时间
Duration time.Duration // 执行耗时
Error error // 执行错误
Skipped bool // 是否被跳过
}
ExecutionResult 执行结果(为了向后兼容保留)
func (*ExecutionResult) ToExecutionContext ¶
func (r *ExecutionResult) ToExecutionContext() *ExecutionContext
ToExecutionContext 将 ExecutionResult 转换为 ExecutionContext
type ExecutionStats ¶
type ExecutionStats struct {
StartTime time.Time // 开始时间
EndTime time.Time // 结束时间
TotalDuration time.Duration // 总耗时
SuccessCount int64 // 成功次数
ErrorCount int64 // 错误次数
SkippedCount int64 // 跳过次数
CancelledCount int64 // 取消次数
}
ExecutionStats 执行统计
type FuncChain ¶
type FuncChain[T any] struct { // contains filtered or unexported fields }
FuncChain 是一个支持可选返回值和错误的函数链
func (*FuncChain[T]) AddFuncItem ¶
AddFuncItem 将 FuncItem 添加到 FuncChain 中
func (*FuncChain[T]) GetFuncItems ¶
GetFuncItems 返回 FuncChain 中的所有 FuncItem(副本)
type FuncItem ¶
type FuncItem[T any] struct { // contains filtered or unexported fields }
FuncItem 表示一个带有优先级的函数
func NewFuncItem ¶
func NewFuncItem[T any](f ReturnFunc[T]) *FuncItem[T]
NewFuncItem 创建一个新的 FuncItem 实例,并设置默认超时和优先级
func (*FuncItem[T]) WithPriority ¶
WithPriority 设置 FuncItem 的优先级
type GoExecutor ¶
type GoExecutor struct {
// contains filtered or unexported fields
}
GoExecutor Goroutine 执行器
func Go ¶
func Go(ctx ...context.Context) *GoExecutor
Go 创建一个新的 Goroutine 执行器 参数 ctx 可选,如果不传或传 nil,则使用 context.Background()
示例:
Go(ctx).OnPanic(handler).Exec(func() { ... })
Go().OnPanic(handler).Exec(func() { ... }) // 使用 background context
Example ¶
示例测试
// 基础执行
Go().Exec(func() {
// 执行任务
})
// 带错误处理
Go().
OnError(func(err error) {
// log.Error(err)
}).
OnPanic(func(r interface{}) {
// log.Error("panic", r)
}).
ExecWithContext(func(ctx context.Context) error {
// 执行可能失败的任务
return nil
})
// 带超时和延迟
Go().
WithTimeout(5 * time.Second).
WithDelay(1 * time.Second).
ExecWithContext(func(ctx context.Context) error {
// 延迟1秒后执行,最多等待5秒
return nil
})
func GoWithContext
deprecated
func GoWithContext(parent context.Context) *GoExecutor
GoWithContext 创建带父 Context 的 Goroutine 执行器(已废弃,使用 Go(ctx) 代替)
示例:
Go(parentCtx).WithTimeout(5*time.Second).ExecWithContext(fn)
Deprecated: 使用 Go(ctx) 代替
func (*GoExecutor) Exec ¶
func (g *GoExecutor) Exec(fn GoExecutorFunc)
Exec 执行无参数的函数
示例:
Go().OnPanic(handler).Exec(func() {
doSomething()
})
func (*GoExecutor) ExecSubs ¶
func (g *GoExecutor) ExecSubs()
ExecSubs 执行所有子 goroutine 任务并等待完成
示例:
Go().OnPanic(handler).
Sub(func() { task1() }).
Sub(func() { task2() }).
SubWithError(func() error { return task3() }).
ExecSubs()
func (*GoExecutor) ExecWithChildren ¶
func (g *GoExecutor) ExecWithChildren(fn func(*ChildRunner))
ExecWithChildren 在父 goroutine 中执行,并管理多个子 goroutine
示例:
Go().OnPanic(handler).ExecWithChildren(func(children *ChildRunner) {
children.Go(func() { startHeartbeat() })
children.Go(func() { subscribe1() })
children.Go(func() { subscribe2() })
})
func (*GoExecutor) ExecWithContext ¶
func (g *GoExecutor) ExecWithContext(fn GoExecutorContextFunc)
ExecWithContext 执行带 Context 的函数
示例:
Go().WithTimeout(5*time.Second).OnError(handler).ExecWithContext(func(ctx context.Context) error {
return repo.Save(ctx, data)
})
func (*GoExecutor) ExecWithResult ¶
func (g *GoExecutor) ExecWithResult(fn GoExecutorResultFunc) <-chan struct { Value interface{} Err error }
ExecWithResult 执行带返回值的函数(异步获取结果)
示例:
resultChan := Go().ExecWithResult(func() (int, error) {
return computeValue(), nil
})
select {
case result := <-resultChan:
if result.Err != nil { ... }
value := result.Value
}
func (*GoExecutor) OnCancel ¶
func (g *GoExecutor) OnCancel(fn GoExecutorCancelHandler) *GoExecutor
OnCancel 设置取消回调
示例:
Go().OnCancel(func() { log.Info("cancelled") }).ExecWithContext(fn)
func (*GoExecutor) OnError ¶
func (g *GoExecutor) OnError(fn GoExecutorErrorHandler) *GoExecutor
OnError 设置错误回调
示例:
Go().OnError(func(err error) { log.Error(err) }).ExecWithContext(fn)
func (*GoExecutor) OnPanic ¶
func (g *GoExecutor) OnPanic(fn GoExecutorPanicHandler) *GoExecutor
OnPanic 设置 panic 回调
示例:
Go().OnPanic(func(r interface{}) { log.Error("panic", r) }).Exec(fn)
func (*GoExecutor) Sub ¶
func (g *GoExecutor) Sub(fn GoExecutorFunc) *GoExecutor
Sub 添加子 goroutine 任务(链式调用)
示例:
Go().OnPanic(handler).
Sub(func() { startHeartbeat() }).
Sub(func() { subscribe1() }).
Sub(func() { subscribe2() }).
ExecSubs()
func (*GoExecutor) SubWithError ¶
func (g *GoExecutor) SubWithError(fn GoExecutorWaitFunc) *GoExecutor
SubWithError 添加带错误返回的子 goroutine 任务(链式调用)
func (*GoExecutor) Wait ¶
func (g *GoExecutor) Wait(fn GoExecutorWaitFunc) error
Wait 同步等待执行完成
示例:
Go().Wait(func() error {
return doSomething()
})
func (*GoExecutor) WithDelay ¶
func (g *GoExecutor) WithDelay(delay time.Duration) *GoExecutor
WithDelay 设置延迟执行时间
示例:
Go().WithDelay(2*time.Second).Exec(fn)
func (*GoExecutor) WithTimeout ¶
func (g *GoExecutor) WithTimeout(timeout time.Duration) *GoExecutor
WithTimeout 设置超时时间
示例:
Go().WithTimeout(5*time.Second).ExecWithContext(fn)
func (*GoExecutor) WithWaitGroup ¶
func (g *GoExecutor) WithWaitGroup(wg *sync.WaitGroup) *GoExecutor
WithWaitGroup 绑定外部 WaitGroup,goroutine 启动前 Add(1),完成后 Done() 用于需要等待异步任务完成的场景(如优雅关闭时等待所有写入完成)
注意:调用方无需手动 Add(1),Exec 系列方法会自动管理计数
示例:
var wg sync.WaitGroup
Go().WithWaitGroup(&wg).WithTimeout(5*time.Second).ExecWithContext(func(ctx context.Context) error {
return repo.Save(ctx, data)
})
wg.Wait() // 等待所有绑定的 goroutine 完成
type GoExecutorContextFunc ¶
GoExecutorContextFunc 带 Context 的执行函数类型
type GoExecutorErrorHandler ¶
type GoExecutorErrorHandler func(error)
GoExecutorErrorHandler 错误处理函数类型
type GoExecutorPanicHandler ¶
type GoExecutorPanicHandler = RecoverFunc
GoExecutorPanicHandler panic 处理函数类型(复用 RecoverFunc)
type GoExecutorResultFunc ¶
type GoExecutorResultFunc func() (interface{}, error)
GoExecutorResultFunc 带返回值的执行函数类型
type HashedWheelTimer ¶
type HashedWheelTimer struct {
// contains filtered or unexported fields
}
HashedWheelTimer 分片时间轮主实现
func NewHashedWheelTimer ¶
func NewHashedWheelTimer(opts ...TimerOption) *HashedWheelTimer
NewHashedWheelTimer 创建分片时间轮
func (*HashedWheelTimer) Cancel ¶
func (t *HashedWheelTimer) Cancel(tt *TimerTask)
Cancel 取消指定任务(惰性取消,O(1))
func (*HashedWheelTimer) CancelByKey ¶
func (t *HashedWheelTimer) CancelByKey(key string)
CancelByKey 按 key 取消任务(惰性取消,O(1))
func (*HashedWheelTimer) Refresh ¶
func (t *HashedWheelTimer) Refresh(key string, delay time.Duration, task func()) *TimerTask
Refresh 刷新任务(O(1) 心跳刷新:取消旧 + 调度新)
func (*HashedWheelTimer) Schedule ¶
func (t *HashedWheelTimer) Schedule(delay time.Duration, task func()) *TimerTask
Schedule 调度一个无 key 的定时任务(轮询分配 shard)
func (*HashedWheelTimer) ScheduleWithKey ¶
func (t *HashedWheelTimer) ScheduleWithKey(key string, delay time.Duration, task func()) *TimerTask
ScheduleWithKey 调度一个带 key 的定时任务(同 key 覆盖会惰性取消旧任务)
func (*HashedWheelTimer) Stats ¶
func (t *HashedWheelTimer) Stats() TimerStats
Stats 返回时间轮统计信息 completed/cancelled 为各 shard 计数器之和(下沉到 shard 避免全局原子竞争)
type Int32 ¶
type Int32 struct {
// contains filtered or unexported fields
}
Int32 类型,使用 atomic.Int32 来表示整数
type Int64 ¶
type Int64 struct {
// contains filtered or unexported fields
}
Int64 类型,使用 atomic.Int64 来表示整数
type LimitedPool ¶
type LimitedPool struct {
// contains filtered or unexported fields
}
LimitedPool 管理多个 levelPool,以支持不同大小的字节切片
func NewLimitedPool ¶
func NewLimitedPool(minSize, maxSize int) *LimitedPool
NewLimitedPool 创建一个新的 LimitedPool,指定最小和最大大小
type Map ¶
type Map[K comparable, V comparable] struct { // contains filtered or unexported fields }
Map 是一个线程安全的映射,使用泛型 K 和 V。
func FromMap ¶
func FromMap[K comparable, V comparable](data map[K]V) *Map[K, V]
FromMap 从普通 map 创建 syncx.Map
func (*Map[K, V]) CompareAndDelete ¶
CompareAndDelete 比较指定键的值,如果相等则删除该键的值。 使用 sync.Map 的原生原子方法,避免 Load+Delete 之间的 TOCTOU 竞争
func (*Map[K, V]) CompareAndSwap ¶
CompareAndSwap 比较指定键的现有值,如果相等则将其替换为新值。 使用 sync.Map 的原生原子方法,避免 Load+Store 之间的 TOCTOU 竞争
func (*Map[K, V]) FilterKeys ¶
FilterKeys 过滤 Map,返回满足条件的键组成的切片
func (*Map[K, V]) GetOrCompute ¶
func (m *Map[K, V]) GetOrCompute(key K, compute func() V) V
GetOrCompute 获取键对应的值,如果不存在则计算并存储
func (*Map[K, V]) GetOrStore ¶
func (m *Map[K, V]) GetOrStore(key K, defaultValue V) V
GetOrStore 获取键对应的值,如果不存在则存储并返回默认值
func (*Map[K, V]) LoadAndDelete ¶
LoadAndDelete 方法从 Map 中加载并删除指定键的值
func (*Map[K, V]) LoadOrStore ¶
LoadOrStore 获取指定键的值,如果不存在则存储新值。
type OrderedSet ¶
type OrderedSet[T comparable] struct { // contains filtered or unexported fields }
OrderedSet 是一个泛型有序集合,元素唯一且保持插入顺序 T 需要是可比较的(comparable),以便用作 map 的键 内部用切片维护顺序,用 map 实现快速存在性判断
func NewOrderedSet ¶
func NewOrderedSet[T comparable]() *OrderedSet[T]
NewOrderedSet 创建一个空的 OrderedSet Returns:
- *OrderedSet[T]:空集合指针
func NewOrderedSetFromSlice ¶
func NewOrderedSetFromSlice[T comparable](items []T) *OrderedSet[T]
NewOrderedSetFromSlice 从给定切片创建 OrderedSet,自动去重且保持顺序 Params:
- items []T:初始化元素切片
Returns:
- *OrderedSet[T]:包含去重元素的集合指针
func (*OrderedSet[T]) Add ¶
func (s *OrderedSet[T]) Add(item T)
Add 添加元素,若元素已存在,则忽略 Params:
- item T:待添加元素
func (*OrderedSet[T]) Contains ¶
func (s *OrderedSet[T]) Contains(item T) bool
Contains 判断元素是否存在 Params:
- item T:待判断元素
Returns:
- bool:存在返回 true,否则 false
func (*OrderedSet[T]) Elements ¶
func (s *OrderedSet[T]) Elements() []T
Elements 返回集合中所有元素的切片,保持插入顺序 Returns:
- []T:元素切片的副本,修改不会影响集合内部状态
func (*OrderedSet[T]) Remove ¶
func (s *OrderedSet[T]) Remove(item T)
Remove 删除元素,若元素不存在,则无操作 Params:
- item T:待删除元素
func (*OrderedSet[T]) String ¶
func (s *OrderedSet[T]) String() string
String 返回集合的字符串表示,便于打印和调试 Returns:
- string:格式如 OrderedSet{elem1, elem2, ...}
type ParallelCompleteCallback ¶
type ParallelCompleteCallback[K comparable, R any] func(map[K]R, map[K]error)
ParallelCompleteCallback 完成回调函数类型 (Map)
type ParallelEachCompleteCallback ¶
type ParallelEachCompleteCallback[K comparable] func(K)
ParallelEachCompleteCallback 每个任务完成回调函数类型 (Map)
type ParallelErrorCallback ¶
type ParallelErrorCallback[K comparable, V any] func(K, V, error)
ParallelErrorCallback 错误回调函数类型 (Map)
type ParallelExecuteFunc ¶
type ParallelExecuteFunc[K comparable, V any, R any] func(K, V) (R, error)
ParallelExecuteFunc 并发执行函数类型 (Map)
type ParallelExecutor ¶
type ParallelExecutor[K comparable, V any, R any] struct { // contains filtered or unexported fields }
ParallelExecutor 并发执行器配置
泛型参数说明:
- K: Map 的键类型 (Key),必须是可比较类型
- V: Map 的值类型 (Value),任意类型
- R: 执行结果类型 (Result),任意类型
示例:
ParallelExecutor[string, *Client, bool] - K=string: 用户ID作为键 - V=*Client: 客户端连接对象 - R=bool: 返回发送是否成功
Example ¶
示例: 真实场景 - 批量发送消息
clients := map[string]string{
"user1": "client1@example.com",
"user2": "client2@example.com",
"user3": "client3@example.com",
}
NewParallelExecutor[string, string, bool](clients).
OnSuccess(func(userID string, email string, sent bool) {
fmt.Printf("✓ 消息已发送到 %s (%s)\n", userID, email)
}).
OnError(func(userID string, email string, err error) {
fmt.Printf("✗ 发送失败 %s: %v\n", userID, err)
}).
OnComplete(func(results map[string]bool, errors map[string]error) {
fmt.Printf("\n总计: 成功 %d, 失败 %d\n", len(results), len(errors))
}).
Execute(func(userID string, email string) (bool, error) {
// 模拟发送消息
if userID == "user2" {
return false, fmt.Errorf("网络超时")
}
return true, nil
})
Output: ✓ 消息已发送到 user1 (client1@example.com) ✗ 发送失败 user2: 网络超时 ✓ 消息已发送到 user3 (client3@example.com) 总计: 成功 2, 失败 1
func NewParallelExecutor ¶
func NewParallelExecutor[K comparable, V any, R any](m map[K]V) *ParallelExecutor[K, V, R]
NewParallelExecutor 创建并发执行器
func (*ParallelExecutor[K, V, R]) Execute ¶
func (p *ParallelExecutor[K, V, R]) Execute(fn ParallelExecuteFunc[K, V, R])
Execute 执行并发任务
func (*ParallelExecutor[K, V, R]) OnComplete ¶
func (p *ParallelExecutor[K, V, R]) OnComplete(fn ParallelCompleteCallback[K, R]) *ParallelExecutor[K, V, R]
OnComplete 设置完成回调(所有任务完成后调用)
func (*ParallelExecutor[K, V, R]) OnEachComplete ¶
func (p *ParallelExecutor[K, V, R]) OnEachComplete(fn ParallelEachCompleteCallback[K]) *ParallelExecutor[K, V, R]
OnEachComplete 设置每个任务完成时的回调
func (*ParallelExecutor[K, V, R]) OnError ¶
func (p *ParallelExecutor[K, V, R]) OnError(fn ParallelErrorCallback[K, V]) *ParallelExecutor[K, V, R]
OnError 设置错误回调
func (*ParallelExecutor[K, V, R]) OnPanic ¶
func (p *ParallelExecutor[K, V, R]) OnPanic(fn ParallelPanicCallback[K, V]) *ParallelExecutor[K, V, R]
OnPanic 设置 panic 回调
func (*ParallelExecutor[K, V, R]) OnSuccess ¶
func (p *ParallelExecutor[K, V, R]) OnSuccess(fn ParallelSuccessCallback[K, V, R]) *ParallelExecutor[K, V, R]
OnSuccess 设置成功回调
type ParallelForEachFunc ¶
type ParallelForEachFunc[K comparable, V any] func(K, V)
ParallelForEachFunc 遍历函数类型 (Map)
type ParallelForEachSliceFunc ¶
ParallelForEachSliceFunc 遍历函数类型 (Slice)
type ParallelPanicCallback ¶
type ParallelPanicCallback[K comparable, V any] func(K, V, any)
ParallelPanicCallback panic 回调函数类型 (Map)
type ParallelSliceCompleteCallback ¶
ParallelSliceCompleteCallback 完成回调函数类型 (Slice)
type ParallelSliceEachCompleteCallback ¶
type ParallelSliceEachCompleteCallback func(int)
ParallelSliceEachCompleteCallback 每个任务完成回调函数类型 (Slice)
type ParallelSliceErrorCallback ¶
ParallelSliceErrorCallback 错误回调函数类型 (Slice)
type ParallelSliceExecuteFunc ¶
ParallelSliceExecuteFunc 并发执行函数类型 (Slice)
type ParallelSliceExecutor ¶
ParallelSliceExecutor 并发 Slice 执行器配置
泛型参数说明:
- T: Slice 元素类型 (Type),任意类型
- R: 执行结果类型 (Result),任意类型
示例:
ParallelSliceExecutor[*Client, int] - T=*Client: 客户端连接对象 - R=int: 返回发送的字节数
Example ¶
示例: Slice 场景 - 批量处理数据
data := []int{10, 20, 30, 40, 50}
NewParallelSliceExecutor[int, int](data).
OnComplete(func(results []int, errors []error) {
// 在 OnComplete 中按顺序输出,保证输出顺序
for i, result := range results {
fmt.Printf("索引 %d: %d -> %d\n", i, data[i], result)
}
fmt.Println("所有任务完成!")
}).
Execute(func(idx int, val int) (int, error) {
return val * 2, nil
})
Output: 索引 0: 10 -> 20 索引 1: 20 -> 40 索引 2: 30 -> 60 索引 3: 40 -> 80 索引 4: 50 -> 100 所有任务完成!
func NewParallelSliceExecutor ¶
func NewParallelSliceExecutor[T any, R any](s []T) *ParallelSliceExecutor[T, R]
NewParallelSliceExecutor 创建并发 Slice 执行器
func (*ParallelSliceExecutor[T, R]) Execute ¶
func (p *ParallelSliceExecutor[T, R]) Execute(fn ParallelSliceExecuteFunc[T, R])
Execute 执行并发任务
工作原理:
- 如果设置了 maxConcurrency,使用信号量控制同时运行的 goroutine 数量
- 所有任务都会被执行,只是控制了并发度
- 使用 WaitGroup 确保所有任务完成后才返回
示例:
- 100个任务,maxConcurrency=10: 同时最多10个 goroutine 在运行,当一个完成后,立即启动下一个 最终所有100个任务都会执行完成
func (*ParallelSliceExecutor[T, R]) OnComplete ¶
func (p *ParallelSliceExecutor[T, R]) OnComplete(fn ParallelSliceCompleteCallback[R]) *ParallelSliceExecutor[T, R]
OnComplete 设置完成回调(所有任务完成后调用)
func (*ParallelSliceExecutor[T, R]) OnEachComplete ¶
func (p *ParallelSliceExecutor[T, R]) OnEachComplete(fn ParallelSliceEachCompleteCallback) *ParallelSliceExecutor[T, R]
OnEachComplete 设置每个任务完成时的回调
func (*ParallelSliceExecutor[T, R]) OnError ¶
func (p *ParallelSliceExecutor[T, R]) OnError(fn ParallelSliceErrorCallback[T]) *ParallelSliceExecutor[T, R]
OnError 设置错误回调
func (*ParallelSliceExecutor[T, R]) OnPanic ¶
func (p *ParallelSliceExecutor[T, R]) OnPanic(fn ParallelSlicePanicCallback[T]) *ParallelSliceExecutor[T, R]
OnPanic 设置 panic 回调
func (*ParallelSliceExecutor[T, R]) OnSuccess ¶
func (p *ParallelSliceExecutor[T, R]) OnSuccess(fn ParallelSliceSuccessCallback[T, R]) *ParallelSliceExecutor[T, R]
OnSuccess 设置成功回调
func (*ParallelSliceExecutor[T, R]) WithConcurrency ¶
func (p *ParallelSliceExecutor[T, R]) WithConcurrency(maxConcurrency int) *ParallelSliceExecutor[T, R]
WithConcurrency 设置最大并发数
参数:
- maxConcurrency: 最大并发 goroutine 数量
- 0: 不限制并发数,所有任务立即启动(默认行为)
- >0: 限制同时运行的 goroutine 数量,使用信号量控制
注意:
- 这只是控制并发数,所有任务最终都会被执行完
- 例如: 100个任务,maxConcurrency=10,表示同时最多10个任务在执行, 当一个任务完成后,会自动启动下一个任务,直到所有100个任务都完成
Example ¶
示例:使用并发控制处理大量任务
// 模拟100个任务,但只允许10个并发
tasks := make([]int, 100)
for i := range tasks {
tasks[i] = i + 1
}
var completed int32
NewParallelSliceExecutor[int, string](tasks).
WithConcurrency(10). // 限制最多10个并发
OnSuccess(func(idx int, val int, result string) {
count := atomic.AddInt32(&completed, 1)
if count%10 == 0 {
fmt.Printf("已完成 %d 个任务\n", count)
}
}).
OnComplete(func(results []string, errors []error) {
fmt.Printf("全部完成!总计 %d 个任务\n", len(results))
}).
Execute(func(idx int, val int) (string, error) {
// 模拟耗时操作
time.Sleep(time.Millisecond)
return fmt.Sprintf("任务 %d 完成", val), nil
})
Output: 已完成 10 个任务 已完成 20 个任务 已完成 30 个任务 已完成 40 个任务 已完成 50 个任务 已完成 60 个任务 已完成 70 个任务 已完成 80 个任务 已完成 90 个任务 已完成 100 个任务 全部完成!总计 100 个任务
type ParallelSlicePanicCallback ¶
ParallelSlicePanicCallback panic 回调函数类型 (Slice)
type ParallelSliceSuccessCallback ¶
ParallelSliceSuccessCallback 成功回调函数类型 (Slice)
type ParallelSuccessCallback ¶
type ParallelSuccessCallback[K comparable, V any, R any] func(K, V, R)
ParallelSuccessCallback 成功回调函数类型 (Map)
type PeriodicTask ¶
type PeriodicTask struct {
// contains filtered or unexported fields
}
PeriodicTask 表示一个周期性任务
func NewPeriodicTask ¶
func NewPeriodicTask(name string, interval time.Duration, executeFunc func(ctx context.Context) error) *PeriodicTask
NewPeriodicTask 创建新的周期性任务
func (*PeriodicTask) GetExecuteFunc ¶
func (t *PeriodicTask) GetExecuteFunc() func(ctx context.Context) error
GetExecuteFunc 获取执行函数
func (*PeriodicTask) GetImmediateStart ¶
func (t *PeriodicTask) GetImmediateStart() bool
GetImmediateStart 获取是否立即执行标志
func (*PeriodicTask) GetInterval ¶
func (t *PeriodicTask) GetInterval() time.Duration
GetInterval 获取执行间隔
func (*PeriodicTask) GetOnError ¶
func (t *PeriodicTask) GetOnError() func(name string, err error)
GetOnError 获取错误处理回调
func (*PeriodicTask) GetOnOverlapSkipped ¶
func (t *PeriodicTask) GetOnOverlapSkipped() func(name string)
GetOnOverlapSkipped 获取重叠跳过回调
func (*PeriodicTask) GetOnStart ¶
func (t *PeriodicTask) GetOnStart() func(name string)
GetOnStart 获取启动回调
func (*PeriodicTask) GetOnStop ¶
func (t *PeriodicTask) GetOnStop() func(name string)
GetOnStop 获取停止回调
func (*PeriodicTask) GetPreventOverlap ¶
func (t *PeriodicTask) GetPreventOverlap() bool
GetPreventOverlap 获取是否防止重叠执行标志
func (*PeriodicTask) IsExecuting ¶
func (t *PeriodicTask) IsExecuting() bool
IsExecuting 获取当前是否正在执行状态
func (*PeriodicTask) SetImmediateStart ¶
func (t *PeriodicTask) SetImmediateStart(immediateStart bool) *PeriodicTask
SetImmediateStart 设置是否立即执行首次任务
func (*PeriodicTask) SetOnError ¶
func (t *PeriodicTask) SetOnError(onError func(name string, err error)) *PeriodicTask
SetOnError 设置错误处理回调
func (*PeriodicTask) SetOnOverlapSkipped ¶
func (t *PeriodicTask) SetOnOverlapSkipped(onOverlapSkipped func(name string)) *PeriodicTask
SetOnOverlapSkipped 设置重叠跳过回调
func (*PeriodicTask) SetOnStart ¶
func (t *PeriodicTask) SetOnStart(onStart func(name string)) *PeriodicTask
SetOnStart 设置启动回调
func (*PeriodicTask) SetOnStop ¶
func (t *PeriodicTask) SetOnStop(onStop func(name string)) *PeriodicTask
SetOnStop 设置停止回调
func (*PeriodicTask) SetPreventOverlap ¶
func (t *PeriodicTask) SetPreventOverlap(preventOverlap bool) *PeriodicTask
SetPreventOverlap 设置是否防止任务重叠执行
type PeriodicTaskManager ¶
type PeriodicTaskManager struct {
// contains filtered or unexported fields
}
PeriodicTaskManager 周期性任务管理器
func NewPeriodicTaskManager ¶
func NewPeriodicTaskManager() *PeriodicTaskManager
NewPeriodicTaskManager 创建新的周期性任务管理器
func (*PeriodicTaskManager) AddSimpleTask ¶
func (m *PeriodicTaskManager) AddSimpleTask(name string, interval time.Duration, executeFunc func(ctx context.Context) error) *PeriodicTaskManager
AddSimpleTask 添加简单的周期性任务
func (*PeriodicTaskManager) AddTask ¶
func (m *PeriodicTaskManager) AddTask(task *PeriodicTask) *PeriodicTaskManager
AddTask 添加周期性任务
func (*PeriodicTaskManager) AddTaskWithImmediateStart ¶
func (m *PeriodicTaskManager) AddTaskWithImmediateStart(name string, interval time.Duration, executeFunc func(ctx context.Context) error) *PeriodicTaskManager
AddTaskWithImmediateStart 添加立即执行的周期性任务
func (*PeriodicTaskManager) AddTaskWithOverlapPrevention ¶
func (m *PeriodicTaskManager) AddTaskWithOverlapPrevention(name string, interval time.Duration, executeFunc func(ctx context.Context) error) *PeriodicTaskManager
AddTaskWithOverlapPrevention 添加防重叠执行的周期性任务
func (*PeriodicTaskManager) AddTaskWithOverlapPreventionAndCallback ¶
func (m *PeriodicTaskManager) AddTaskWithOverlapPreventionAndCallback( name string, interval time.Duration, executeFunc func(ctx context.Context) error, onOverlapSkipped func(name string), ) *PeriodicTaskManager
AddTaskWithOverlapPreventionAndCallback 添加防重叠执行的周期性任务(带重叠跳过回调)
func (*PeriodicTaskManager) AddTaskWithOverlapPreventionImmediateAndCallback ¶
func (m *PeriodicTaskManager) AddTaskWithOverlapPreventionImmediateAndCallback( name string, interval time.Duration, executeFunc func(ctx context.Context) error, onOverlapSkipped func(name string), ) *PeriodicTaskManager
AddTaskWithOverlapPreventionImmediateAndCallback 添加防重叠执行的周期性任务(带立即执行和重叠跳过回调)
func (*PeriodicTaskManager) ClearAllTasks ¶
func (m *PeriodicTaskManager) ClearAllTasks()
ClearAllTasks 清除所有任务
func (*PeriodicTaskManager) GetTaskCount ¶
func (m *PeriodicTaskManager) GetTaskCount() int
GetTaskCount 获取任务数量
func (*PeriodicTaskManager) GetTaskDetails ¶
func (m *PeriodicTaskManager) GetTaskDetails(name ...string) []TaskDetailInfo
GetTaskDetails 获取任务详细信息 如果name为空,返回所有任务;如果指定name,返回匹配的任务
func (*PeriodicTaskManager) GetTaskNames ¶
func (m *PeriodicTaskManager) GetTaskNames() []string
GetTaskNames 获取所有任务名称
func (*PeriodicTaskManager) IsRunning ¶
func (m *PeriodicTaskManager) IsRunning() bool
IsRunning 检查任务管理器是否正在运行
func (*PeriodicTaskManager) RemoveTask ¶
func (m *PeriodicTaskManager) RemoveTask(name string) bool
RemoveTask 移除指定名称的任务
func (*PeriodicTaskManager) RemoveTaskWithTimeout ¶
func (m *PeriodicTaskManager) RemoveTaskWithTimeout(name string, timeout time.Duration) bool
RemoveTaskWithTimeout 移除指定名称的任务(带超时等待)
func (*PeriodicTaskManager) SetDefaultCallbacks ¶
func (m *PeriodicTaskManager) SetDefaultCallbacks( onStart func(name string), onStop func(name string), ) *PeriodicTaskManager
SetDefaultCallbacks 设置默认回调函数
func (*PeriodicTaskManager) SetDefaultErrorHandler ¶
func (m *PeriodicTaskManager) SetDefaultErrorHandler(handler func(name string, err error)) *PeriodicTaskManager
SetDefaultErrorHandler 设置默认错误处理器
func (*PeriodicTaskManager) StartWithContext ¶
func (m *PeriodicTaskManager) StartWithContext(ctx context.Context) error
StartWithContext 使用指定上下文启动所有周期性任务
func (*PeriodicTaskManager) StopWithTimeout ¶
func (m *PeriodicTaskManager) StopWithTimeout(timeout time.Duration) error
StopWithTimeout 在指定超时时间内停止所有周期性任务
func (*PeriodicTaskManager) WaitForExecution ¶
func (m *PeriodicTaskManager) WaitForExecution(timeout time.Duration) error
WaitForExecution 等待所有任务至少执行一次 timeout: 最大等待时间,0表示无限等待
type PoolOption ¶
type PoolOption func(*WorkerPool)
PoolOption Worker 池选项函数
func WithPoolIdleTimeout ¶
func WithPoolIdleTimeout(d time.Duration) PoolOption
WithPoolIdleTimeout 设置空闲 worker 自动回收超时 不设置时使用 defaultPoolIdleTimeout(60s),仅影响回收节奏不影响并发上限
func WithWorkerPoolPanicHandler ¶
func WithWorkerPoolPanicHandler(handler RecoverFunc) PoolOption
WithWorkerPoolPanicHandler 设置 panic 恢复处理器 任务 panic 时调用 handler,handler 为 nil 时仅 recover 不记录(防止进程崩溃)
type RLocker ¶
type RLocker interface {
Lock()
Unlock()
RLock()
RUnlock()
}
RLocker 是一个接口,定义了读锁和解锁的方法
type Set ¶
type Set[K comparable] struct { // contains filtered or unexported fields }
Set 是一个线程安全的集合,使用 Map 实现。
type ShardedMap ¶
type ShardedMap[K comparable, V any] struct { // contains filtered or unexported fields }
ShardedMap 分片映射表 将 key 按 hash 分散到 N 个 shard,每个 shard 独立锁 适用于高并发读写场景,相比 sync.Map:
- 写性能更好(多 shard 分散锁竞争)
- Range 性能更好(可并行遍历不同 shard)
- Len 性能更好(原子计数,无需遍历)
func NewShardedMap ¶
func NewShardedMap[K comparable, V any](shardCount int) *ShardedMap[K, V]
NewShardedMap 创建分片映射表(无预分配容量)
参数:
- shardCount: 分片数量,必须是 2 的幂(如 32/64/128)
返回:*ShardedMap[K, V]
注意:每个 shard 内部 map 不预分配容量,适用于容量未知或较小的场景 已知总容量的大数据场景请使用 NewShardedMapWithOptions 配合 WithPerShardHint
func NewShardedMapWithOptions ¶
func NewShardedMapWithOptions[K comparable, V any](shardCount int, opts ...ShardedMapOption[K, V]) *ShardedMap[K, V]
NewShardedMapWithOptions 创建分片映射表(支持配置选项)
参数:
- shardCount: 分片数量,必须是 2 的幂(如 32/64/128)
- opts: 配置选项(如 WithPerShardHint)
返回:*ShardedMap[K, V]
func (*ShardedMap[K, V]) ClearHalf ¶
func (m *ShardedMap[K, V]) ClearHalf()
ClearHalf 随机清空每个 shard 内一半的元素
用于大容量缓存的超限驱逐:相比整表 Clear 保留一半数据,避免缓存命中率雪崩 (重建窗口内的查询全部回源),驱逐成本相同(无 LRU 链表维护开销) 每 shard 独立驱逐一半(map 遍历序随机),无轮换状态、多次调用持续有效
func (*ShardedMap[K, V]) CompareAndDelete ¶
func (m *ShardedMap[K, V]) CompareAndDelete(key K, value V) bool
CompareAndDelete 原子比较并删除 仅当 key 存在且当前值等于 value 时,才删除 注意:V 为非可比较类型(如 slice/map)时会 panic,与 sync.Map 行为一致
func (*ShardedMap[K, V]) CompareAndSwap ¶
func (m *ShardedMap[K, V]) CompareAndSwap(key K, old, new V) bool
CompareAndSwap 原子比较并交换 仅当 key 存在且当前值等于 old 时,才替换为 new 注意:V 为非可比较类型(如 slice/map)时会 panic,与 sync.Map 行为一致
func (*ShardedMap[K, V]) Count ¶
func (m *ShardedMap[K, V]) Count(filter func(K, V) bool) int
Count 返回满足条件的元素数量 filter 为 nil 时等价于 Len
func (*ShardedMap[K, V]) Load ¶
func (m *ShardedMap[K, V]) Load(key K) (V, bool)
Load 加载 key 的 value 返回:(value, exists)
func (*ShardedMap[K, V]) LoadAndDelete ¶
func (m *ShardedMap[K, V]) LoadAndDelete(key K) (V, bool)
LoadAndDelete 加载并删除 返回:(value, exists)
func (*ShardedMap[K, V]) LoadOrStore ¶
func (m *ShardedMap[K, V]) LoadOrStore(key K, value V) (V, bool)
LoadOrStore 加载或存储 如果 key 存在返回 (existing, true),否则存储 value 并返回 (value, false)
func (*ShardedMap[K, V]) Range ¶
func (m *ShardedMap[K, V]) Range(fn func(key K, value V) bool)
Range 遍历所有键值对 遍历期间每个 shard 持有读锁(分片粒度,不影响其他 shard 写入) fn 返回 false 时停止遍历
func (*ShardedMap[K, V]) RangeParallel ¶
func (m *ShardedMap[K, V]) RangeParallel(workerNum int, fn func(key K, value V))
RangeParallel 并行遍历所有键值对(百万级数据优化)
将 shards 分配到 workerNum 个 goroutine 并行遍历,每个 goroutine 独立持有所分配 shard 的读锁。 不同 goroutine 处理不同 shard,读锁无竞争;同一 shard 仅被一个 goroutine 读取,零锁争用。
对比 Range(串行遍历):百万级数据提速数倍,不需要 Keys() 那样的中间切片
实测(Apple M4,10 核,一百万个 int 键值对,64 shard):
回调内容 Range RangeParallel 本地累加(无争用) 5.91 ms 1.56 ms 快 3.8 倍 atomic.Int64.Add(共享计数器) 6.17 ms 44.2 ms 慢 7.2 倍
**fn 里的争用会把并行的收益吃光并倒转**:十个 goroutine 抢同一个原子计数器时, 缓存行在核间来回弹跳的代价远超并行省下的时间,比串行还慢七倍 想累加就让每个 goroutine 写各自的槽位(例如按 key 分桶),遍历结束再合并; 往同一个 channel 发、抢同一把锁、累加同一个计数器都属于这一类 换句话说「提速数倍」的前提是 fn 之间互不干扰,而这一条比并行本身更决定结果
[EN] Several times faster than Range on million-scale data, with no intermediate slice. Measured on an Apple M4 with 10 cores and one million int pairs across 64 shards: a contention-free callback runs 5.91 ms serially against 1.56 ms in parallel, a 3.8x gain, while a callback adding to one shared atomic.Int64 runs 6.17 ms serially against 44.2 ms in parallel — 7.2x *slower*. Contention inside fn does not merely erase the gain, it inverts it: ten goroutines bouncing one cache line between cores cost far more than parallelism saves. Accumulate into per-goroutine slots and merge afterwards; sending to one channel, taking one lock or incrementing one counter all fall into the same trap. The promised speedup is conditional on fn not interfering with itself, and that condition matters more than the parallelism
注意:
- fn 无返回值(始终遍历全部),不支持提前终止——并行场景下"全局停止"语义不明确
- fn 在持有 shard 读锁时执行,应为非阻塞操作(TrySend 等非阻塞操作可安全调用)
- workerNum <= 0 时使用 GOMAXPROCS;shard 数量少于 worker 时退化为按 shard 数并行
func (*ShardedMap[K, V]) Store ¶
func (m *ShardedMap[K, V]) Store(key K, value V)
Store 存储 key→value
func (*ShardedMap[K, V]) StoreBatch ¶
func (m *ShardedMap[K, V]) StoreBatch(items map[K]V)
StoreBatch 批量存储,按 shard 分组减少锁获取次数 相比逐个 Store,N 个元素分散到 S 个 shard 时锁获取次数从 N 降到 S
分组用计数排序而不是 map 嵌 map
原先为每个 shard 建一个 map[K]V 来装它的那批键,一千个元素分到 64 个 shard 要分配 451 次;而 shard 下标本就是 [0, shardCount) 的小整数, 计数排序两趟即可把元素按 shard 排好,总共三次分配
为什么保留分组而不是干脆逐项 Store:量过两种写法,结论随 shard 数翻转—— 64 个 shard 时逐项更快(争用小,省下的是建表开销), 但 8 个 shard 并发写时逐项反而慢一倍(十个 goroutine 抢八把锁,争用占主导,一千次加锁远贵于一次) 分组的价值在争用大的那一侧,去掉分配之后两侧都不亏
[EN] Grouping is done with a counting sort rather than a map of maps. The previous version built one map[K]V per shard, which cost 451 allocations for a thousand elements across 64 shards, even though a shard index is just a small integer in [0, shardCount) that two passes can order by. Grouping itself is kept rather than falling back to per-item Store because the two were measured and the winner flips with the shard count: per-item is faster with 64 shards, where contention is low and the saving is the bookkeeping, but half as fast with 8 shards under concurrent writers, where ten goroutines contend for eight locks and a thousand acquisitions cost far more than one. Grouping earns its keep on the contended side, and without the allocations neither side loses StoreBatch 批量写入
元素较多时按 shard 分组,每个 shard 只加锁一次,把加锁次数从 len(items) 降到 最多 shardCount 次分组用计数排序,两趟线性扫描,不做比较排序
分组并非总是更快,阈值取 shardCount
分组省下来的是「多个元素落进同一个 shard」时的重复加锁,所以只有 len(items) 明显大于 shardCount 时才有的省元素更少时多数 shard 只摊到一个 元素,省不下任何一次加锁,却要先付三次切片分配(entries/counts/sorted) 实测(Apple M4,10 并发,ns/op,越小越好):
元素数 8 分片 逐项/分组 64 分片 逐项/分组 8 426 / 375 290 / 396 16 917 / 549 539 / 632 32 1829 / 848 913 / 1115 64 4029 / 1498 1897 / 1747 ← 64 分片的交点 512 34825 / 11060 15759 / 10993
两种分片数的交点都落在 len(items) ≈ shardCount 上,与上面的机理一致 无争用的单协程场景加锁只是几纳秒的原子操作,分组要到约 512 项才扳平, 因此这个阈值偏向争用场景——分片 map 本来就是为争用而存在的
[EN] Bulk store. With enough items it groups them by shard with a counting sort so each shard is locked once, cutting lock acquisitions from len(items) to at most shardCount.
Grouping is not always faster, and the threshold is shardCount. What grouping saves is the repeated locking when several items land in the same shard, so it only pays off once len(items) clearly exceeds shardCount; below that most shards hold a single item, no lock acquisition is saved, and three slice allocations are spent for nothing. Measured on an Apple M4 at 10-way parallelism, both shard counts cross over at len(items) ~ shardCount. With no contention at all grouping needs about 512 items to break even, so this threshold favours the contended case — which is what a sharded map is for
func (*ShardedMap[K, V]) Swap ¶
func (m *ShardedMap[K, V]) Swap(key K, value V) (V, bool)
Swap 替换 key 的值并返回之前的值 如果 key 不存在,存储新值并返回零值和 false
func (*ShardedMap[K, V]) WithShardLock ¶
func (m *ShardedMap[K, V]) WithShardLock(key K, fn func(shardData map[K]V))
WithShardLock 在 key 对应的 shard 锁内执行操作(写锁) 用于需要在同一 shard 内原子操作多个 map 的场景
func (*ShardedMap[K, V]) WithShardRLock ¶
func (m *ShardedMap[K, V]) WithShardRLock(key K, fn func(shardData map[K]V))
WithShardRLock 在 key 对应的 shard 读锁内执行操作(读锁)
type ShardedMapOption ¶
type ShardedMapOption[K comparable, V any] func(*shardedMapConfig)
ShardedMapOption ShardedMap 配置选项(修改内部 config)
func WithPerShardHint ¶
func WithPerShardHint[K comparable, V any](perShardHint int) ShardedMapOption[K, V]
WithPerShardHint 设置每个 shard 内部 map 的预分配容量提示
用于已知总容量的场景,减少 shard 内部 map 扩容次数,提升写入性能 建议值:预估总元素数 / shardCount(向上取整)
示例:总容量 10000,分 64 个 shard,每 shard 提示 = 10000/64 ≈ 157
type SimpleTaskFunc ¶
type SimpleTaskFunc func(ctx *ExecutionContext) error
SimpleTaskFunc 简单任务函数类型(无返回值)
type StateMachine ¶
type StateMachine[S comparable] struct { // contains filtered or unexported fields }
Example ¶
示例测试
// 创建连接状态机
sm := NewStateMachine(StateDisconnected)
// 配置允许的状态转换
sm.AllowTransition(StateDisconnected, StateConnecting)
sm.AllowTransition(StateConnecting, StateConnected)
sm.AllowTransition(StateConnecting, StateDisconnected)
sm.AllowTransition(StateConnected, StateDisconnected)
// 注册状态转换回调
sm.OnTransition(func(from, to ConnectionState) {
// log.Printf("State: %s -> %s", from, to)
})
// 执行状态转换
_ = sm.TransitionTo(StateConnecting)
_ = sm.TransitionTo(StateConnected)
func NewStateMachine ¶
func NewStateMachine[S comparable](initialState S, opts ...StateMachineOption[S]) *StateMachine[S]
NewStateMachine 创建一个新的状态机 initialState 为初始状态
示例:
sm := NewStateMachine("idle")
sm := NewStateMachine("idle", WithAllowAnyTransition()) // 允许任意转换
func (*StateMachine[S]) AllowTransition ¶
func (sm *StateMachine[S]) AllowTransition(from, to S)
AllowTransition 允许从状态 from 转换到状态 to 可以多次调用以配置状态转换规则
示例:
sm.AllowTransition("pending", "approved")
sm.AllowTransition("pending", "rejected")
func (*StateMachine[S]) AllowTransitions ¶
func (sm *StateMachine[S]) AllowTransitions(from S, toStates ...S)
AllowTransitions 批量允许状态转换 参数 from 为起始状态, toStates 为可转换到的所有目标状态
示例:
sm.AllowTransitions("pending", "approved", "rejected", "cancelled")
func (*StateMachine[S]) CanTransitionTo ¶
func (sm *StateMachine[S]) CanTransitionTo(to S) bool
CanTransitionTo 检查是否可以转换到目标状态 线程安全
示例:
if sm.CanTransitionTo("approved") {
可以转换
}
func (*StateMachine[S]) ClearCallbacks ¶
func (sm *StateMachine[S]) ClearCallbacks()
ClearCallbacks 清除所有回调函数
func (*StateMachine[S]) ClearHistory ¶
func (sm *StateMachine[S]) ClearHistory()
ClearHistory 清除历史记录
func (*StateMachine[S]) CurrentState ¶
func (sm *StateMachine[S]) CurrentState() S
CurrentState 获取当前状态 线程安全
func (*StateMachine[S]) DisallowTransition ¶
func (sm *StateMachine[S]) DisallowTransition(from, to S)
DisallowTransition 禁止从状态 from 转换到状态 to
func (*StateMachine[S]) GetAllowedTransitions ¶
func (sm *StateMachine[S]) GetAllowedTransitions() []S
GetAllowedTransitions 获取当前状态允许转换到的所有状态
func (*StateMachine[S]) GetHistory ¶
func (sm *StateMachine[S]) GetHistory() []StateTransition[S]
GetHistory 获取状态转换历史记录 返回所有历史记录的副本,按时间顺序排列(最早的在前)
示例:
history := sm.GetHistory()
for _, trans := range history {
fmt.Printf("%s: %v -> %v\n", trans.Timestamp.Format(time.RFC3339), trans.From, trans.To)
}
func (*StateMachine[S]) GetHistoryCount ¶
func (sm *StateMachine[S]) GetHistoryCount() int
GetHistoryCount 获取历史记录数量
func (*StateMachine[S]) GetHistoryString ¶
func (sm *StateMachine[S]) GetHistoryString() string
GetHistoryString 获取完整执行流程的字符串表示 使用创建状态机时配置的时间格式 返回格式化后的历史记录字符串,每行一条记录
示例:
historyStr := sm.GetHistoryString() fmt.Println(historyStr)
func (*StateMachine[S]) GetLastTransition ¶
func (sm *StateMachine[S]) GetLastTransition() (StateTransition[S], bool)
GetLastTransition 获取最后一次状态转换记录 如果没有历史记录,返回零值和 false
func (*StateMachine[S]) GetLastTransitionDuration ¶
func (sm *StateMachine[S]) GetLastTransitionDuration() time.Duration
GetLastTransitionDuration 获取上次状态转换的持续时间(在上一个状态停留的时间) 如果没有历史记录,返回 0
func (*StateMachine[S]) GetLastTransitionTime ¶
func (sm *StateMachine[S]) GetLastTransitionTime() time.Time
GetLastTransitionTime 获取上次状态转换的时间
func (*StateMachine[S]) GetRecentHistory ¶
func (sm *StateMachine[S]) GetRecentHistory(n int) []StateTransition[S]
GetRecentHistory 获取最近 n 条状态转换历史记录 如果 n 大于实际历史记录数量,返回所有历史记录
示例:
recentHistory := sm.GetRecentHistory(5) // 获取最近5条记录
func (*StateMachine[S]) GetRecentHistoryString ¶
func (sm *StateMachine[S]) GetRecentHistoryString(n int) string
GetRecentHistoryString 获取最近 n 条执行流程的字符串表示 n 为记录数量,使用创建状态机时配置的时间格式
示例:
historyStr := sm.GetRecentHistoryString(5)
func (*StateMachine[S]) GetTotalDuration ¶
func (sm *StateMachine[S]) GetTotalDuration() time.Duration
GetTotalDuration 获取从状态机创建到当前的总时长
func (*StateMachine[S]) IsTrackingHistory ¶
func (sm *StateMachine[S]) IsTrackingHistory() bool
IsTrackingHistory 检查是否正在追踪历史记录
func (*StateMachine[S]) MustTransitionTo ¶
func (sm *StateMachine[S]) MustTransitionTo(to S)
MustTransitionTo 强制转换到目标状态,如果失败则 panic
func (*StateMachine[S]) OnEnter ¶
func (sm *StateMachine[S]) OnEnter(state S, handler func(from S))
OnEnter 注册进入某个状态时的回调 参数 from 为转换前的状态
示例:
sm.OnEnter("connected", func(from string) {
log.Printf("Entered connected state from %s", from)
})
func (*StateMachine[S]) OnExit ¶
func (sm *StateMachine[S]) OnExit(state S, handler func(to S))
OnExit 注册离开某个状态时的回调 参数 to 为转换后的目标状态
示例:
sm.OnExit("connected", func(to string) {
log.Printf("Exiting connected state to %s", to)
})
func (*StateMachine[S]) OnTransition ¶
func (sm *StateMachine[S]) OnTransition(handler func(from, to S))
OnTransition 注册状态转换回调 每次状态转换时都会调用所有已注册的回调函数
示例:
sm.OnTransition(func(from, to string) {
log.Printf("State changed: %s -> %s", from, to)
})
func (*StateMachine[S]) TransitionTo ¶
func (sm *StateMachine[S]) TransitionTo(to S) error
TransitionTo 转换到目标状态 如果转换不被允许,返回错误 转换成功时会触发所有已注册的回调函数
示例:
if err := sm.TransitionTo("approved"); err != nil {
log.Printf("Transition failed: %v", err)
}
type StateMachineOption ¶
type StateMachineOption[S comparable] func(*StateMachine[S])
StateMachineOption 状态机配置选项
func WithAllowAnyTransition ¶
func WithAllowAnyTransition[S comparable]() StateMachineOption[S]
WithAllowAnyTransition 允许任意状态转换
func WithTimeFormat ¶
func WithTimeFormat[S comparable](timeFormat string) StateMachineOption[S]
WithTimeFormat 设置历史记录的时间格式 timeFormat 为时间格式字符串,默认使用 time.RFC3339
示例:
sm := NewStateMachine("idle", WithTrackHistory(100), WithTimeFormat("2006-01-02 15:04:05"))
func WithTrackHistory ¶
func WithTrackHistory[S comparable](maxHistory int) StateMachineOption[S]
WithTrackHistory 启用历史记录追踪 maxHistory 为最大历史记录数量,0表示不限制
示例:
sm := NewStateMachine("idle", WithTrackHistory(100)) // 最多保留100条历史
sm := NewStateMachine("idle", WithTrackHistory(0)) // 不限制历史记录数量
type StateTransition ¶
type StateTransition[S comparable] struct { From S // 转换前状态 To S // 转换后状态 Timestamp time.Time // 转换时间 Duration time.Duration // 在 From 状态停留的时间 }
StateTransition 状态转换记录
type Task ¶
Task 表示一个异步任务
func NewTaskWithOptions ¶
func NewTaskWithOptions[T any, R any, U any](name string, fn TaskExecuteFunc[T, R], input T, ctx context.Context, maxRetries int32, retryInterval time.Duration) *Task[T, R, U]
NewTaskWithOptions 创建一个新的任务
func (*Task[T, R, U]) AddDependency ¶
AddDependency 添加依赖关系
func (*Task[T, R, U]) GetCallbackDuration ¶
GetCallbackDuration 获取回调运行时间
func (*Task[T, R, U]) GetCallbackError ¶
GetCallbackError 获取回调错误
func (*Task[T, R, U]) GetCallbackResult ¶
func (tk *Task[T, R, U]) GetCallbackResult() U
GetCallbackResult 获取回调结果
func (*Task[T, R, U]) GetCallbackState ¶
GetCallbackState 获取回调状态
func (*Task[T, R, U]) GetDependExecutionMode ¶
func (tk *Task[T, R, U]) GetDependExecutionMode() ExecutionMode
GetDependExecutionMode 获取依赖任务的执行模式
func (*Task[T, R, U]) GetDependencyStates ¶
GetDependencyStates 获取所有依赖任务的状态
func (*Task[T, R, U]) GetDepends ¶
GetDepends 获取当前任务的所有依赖任务
func (*Task[T, R, U]) GetFnDuration ¶
GetFnDuration 获取主任务运行时间
func (*Task[T, R, U]) GetMaxRetries ¶
GetMaxRetries 获取最大重试次数
func (*Task[T, R, U]) GetRetryCount ¶
GetRetryCount 获取任务失败后重试次数
func (*Task[T, R, U]) GetTaskHistory ¶
func (tk *Task[T, R, U]) GetTaskHistory(taskName string) []TaskHistory
GetTaskHistory 获取任务执行历史
func (*Task[T, R, U]) GetTaskType ¶
GetTaskType 获取任务类型
func (*Task[T, R, U]) GetTimestamp ¶
GetTimestamp 获取任务开始时间戳(纳秒)
func (*Task[T, R, U]) GetTotalDuration ¶
GetTotalDuration 获取任务的总耗时
func (*Task[T, R, U]) SetDependExecutionMode ¶
func (tk *Task[T, R, U]) SetDependExecutionMode(executionMode ExecutionMode) *Task[T, R, U]
SetDependExecutionMode 设置依赖任务的执行模式,并返回当前任务以支持链式调用
func (*Task[T, R, U]) SetFailureCallback ¶
func (tk *Task[T, R, U]) SetFailureCallback(callback TaskCallbackFunc[R, U]) *Task[T, R, U]
SetFailureCallback 设置任务失败后的回调函数,并返回当前任务以支持链式调用
func (*Task[T, R, U]) SetMaxHistorySize ¶
SetMaxHistorySize 设置最大历史记录行到 TaskManager
func (*Task[T, R, U]) SetMaxRetries ¶
SetMaxRetries 设置最大重试次数,并返回当前任务以支持链式调用
func (*Task[T, R, U]) SetPriority ¶
SetPriority 设置任务优先级,并返回当前任务以支持链式调用
func (*Task[T, R, U]) SetRetryInterval ¶
SetRetryInterval 设置任务失败后重试间隔时间,并返回当前任务以支持链式调用
func (*Task[T, R, U]) SetSuccessCallback ¶
func (tk *Task[T, R, U]) SetSuccessCallback(callback TaskCallbackFunc[R, U]) *Task[T, R, U]
SetSuccessCallback 设置任务成功后的回调函数,并返回当前任务以支持链式调用
type TaskCallbackFunc ¶
TaskCallbackFunc 任务回调函数类型
type TaskDetailInfo ¶
type TaskDetailInfo struct {
Name string `json:"name"`
Interval time.Duration `json:"interval"`
ImmediateStart bool `json:"immediate_start"`
PreventOverlap bool `json:"prevent_overlap"`
IsExecuting bool `json:"is_executing"`
}
TaskDetailInfo 任务详细信息
type TaskExecuteFunc ¶
TaskExecuteFunc 任务执行函数类型
type TaskHistory ¶
type TaskHistory struct {
// contains filtered or unexported fields
}
TaskHistory 记录任务执行的历史信息
func (*TaskHistory) GetCallbackDuration ¶
func (th *TaskHistory) GetCallbackDuration() time.Duration
GetCallbackDuration 获取回调函数的执行时间
func (*TaskHistory) GetFnDuration ¶
func (th *TaskHistory) GetFnDuration() time.Duration
GetFnDuration 获取任务函数的执行时间
func (*TaskHistory) GetTimestamp ¶
func (th *TaskHistory) GetTimestamp() int64
GetTimestamp 获取任务执行的时间戳
type TaskManager ¶
TaskManager 管理所有的任务
func NewTaskManager ¶
func NewTaskManager[T any, R any, U any](concurrency int) *TaskManager[T, R, U]
NewTaskManager 创建一个新的 TaskManager
func (*TaskManager[T, R, U]) AddTask ¶
func (tm *TaskManager[T, R, U]) AddTask(task *Task[T, R, U]) *TaskManager[T, R, U]
AddTask 添加一个任务到 TaskManager
func (*TaskManager[T, R, U]) Cancel ¶
func (tm *TaskManager[T, R, U]) Cancel(taskName string)
Cancel 取消某个任务
func (*TaskManager[T, R, U]) CancelAll ¶
func (tm *TaskManager[T, R, U]) CancelAll()
CancelAll 取消所有任务
func (*TaskManager[T, R, U]) GetTask ¶
func (tm *TaskManager[T, R, U]) GetTask(name string) (*Task[T, R, U], bool)
GetTask 获取指定名称的任务(线程安全)
func (*TaskManager[T, R, U]) GetTasks ¶
func (tm *TaskManager[T, R, U]) GetTasks() map[string]*Task[T, R, U]
GetTasks 获取所有任务的快照副本(避免外部并发修改内部 map)
func (*TaskManager[T, R, U]) SetTrunDown ¶
func (tm *TaskManager[T, R, U]) SetTrunDown(fn TaskTrunFunc[R]) *TaskManager[T, R, U]
SetTrunDown 设置关闭时执行的函数
func (*TaskManager[T, R, U]) SetTrunUp ¶
func (tm *TaskManager[T, R, U]) SetTrunUp(fn TaskTrunFunc[R]) *TaskManager[T, R, U]
SetTrunUp 设置启动时执行的函数
func (*TaskManager[T, R, U]) TrunDown ¶
func (tm *TaskManager[T, R, U]) TrunDown() (result R, err error)
TrunDown 关闭任务管理器并返回结果和错误
func (*TaskManager[T, R, U]) TrunUp ¶
func (tm *TaskManager[T, R, U]) TrunUp() (result R, err error)
TrunUp 启动任务管理器并返回结果和错误
type TaskProgressFunc ¶
TaskProgressFunc 任务进度回调函数类型
type Timer ¶
type Timer interface {
// Schedule 调度一个无 key 的定时任务(轮询分配 shard)
Schedule(delay time.Duration, task func()) *TimerTask
// ScheduleWithKey 调度一个带 key 的定时任务(同 key 覆盖会惰性取消旧任务)
ScheduleWithKey(key string, delay time.Duration, task func()) *TimerTask
// Refresh 刷新任务(O(1) 心跳刷新:取消旧 + 调度新,等价于 ScheduleWithKey)
Refresh(key string, delay time.Duration, task func()) *TimerTask
// Cancel 取消指定任务(惰性取消,O(1))
Cancel(t *TimerTask)
// CancelByKey 按 key 取消任务(惰性取消,O(1))
CancelByKey(key string)
// Stop 停止时间轮(停止所有 worker,不再执行待触发任务)
Stop()
// Stats 返回时间轮统计信息
Stats() TimerStats
}
Timer 时间轮定时器接口
type TimerOption ¶
type TimerOption func(*timerConfig)
TimerOption 时间轮配置选项
func WithTimerBucketCount ¶
func WithTimerBucketCount(count int) TimerOption
WithTimerBucketCount 设置每分片 bucket 数量(必须是 2 的幂)
func WithTimerExecutor ¶
func WithTimerExecutor(fn func(func())) TimerOption
WithTimerExecutor 设置回调执行器
func WithTimerShardCount ¶
func WithTimerShardCount(count int) TimerOption
WithTimerShardCount 设置分片数量(必须是 2 的幂)
func WithTimerTickInterval ¶
func WithTimerTickInterval(d time.Duration) TimerOption
WithTimerTickInterval 设置 tick 间隔
type TimerStats ¶
type TimerStats struct {
ActiveTasks int64 // 活跃任务数
CompletedTasks int64 // 已完成任务数(已执行回调)
CancelledTasks int64 // 已取消任务数(惰性取消)
}
TimerStats 时间轮统计信息
type TimerTask ¶
type TimerTask struct {
// contains filtered or unexported fields
}
TimerTask 时间轮任务(双向链表节点)
type TryRLocker ¶
TryRLocker 支持 TryRLock 的读锁接口
type Uint32 ¶
type Uint32 struct {
// contains filtered or unexported fields
}
Uint32 类型,使用 atomic.Uint32 来表示无符号整数
type Uint64 ¶
type Uint64 struct {
// contains filtered or unexported fields
}
Uint64 类型,使用 atomic.Uint64 来表示无符号整数
type Uintptr ¶
type Uintptr struct {
// contains filtered or unexported fields
}
Uintptr 类型,使用 atomic.Uintptr 来表示无符号指针
type WorkerPool ¶
type WorkerPool struct {
// contains filtered or unexported fields
}
WorkerPool 弹性 Worker 池,用于限制并发 goroutine 数量 防止高频操作导致 goroutine 无限增长导致 OOM
弹性策略(并发上限 workers 不变,按需伸缩):
- 构造时仅启动保底数量 worker(min(4, workers)),而非全量启动
- Submit 发现队列有积压时按需补充 worker(不超过 workers 上限)
- worker 空闲超过 idleTimeout 自动退出(回收后不低于保底数量)
使用场景:
- PubSub 消息处理
- 高频任务分发
- 并发控制
示例:
pool := NewWorkerPool(20, 100)
defer pool.Close()
for i := 0; i < 1000; i++ {
err := pool.Submit(ctx, func() {
处理任务
})
if err != nil {
log.Errorf("submit failed: %v", err)
}
}
func NewWorkerPool ¶
func NewWorkerPool(workers, queueSize int, opts ...PoolOption) *WorkerPool
NewWorkerPool 创建 Worker 池 workers: worker 数量,建议 10-50,根据 CPU 核心数调整 queueSize: 任务队列大小,建议 100-1000 opts: 可选配置(如 WithWorkerPoolPanicHandler)
示例:
创建 20 个 worker,队列大小 100 pool := NewWorkerPool(20, 100) defer pool.Close()
带 panic 恢复处理器:
pool := NewWorkerPool(20, 100, WithWorkerPoolPanicHandler(func(r interface{}) {
log.Error("worker panic recovered", "panic", r)
}))
func (*WorkerPool) Close ¶
func (p *WorkerPool) Close() error
Close 关闭 Worker 池,等待所有任务完成 调用此方法后,所有新的提交都会返回 ErrClosed
注意:不关闭 queue channel,避免 Submit 在检查 closed 标志后 仍向已关闭 channel 发送数据导致 panic。worker 通过 ctx.Done() 退出
示例:
pool := NewWorkerPool(20, 100) 提交任务 ... pool.Close() // 等待所有任务完成后返回
func (*WorkerPool) GetActiveWorkerCount ¶
func (p *WorkerPool) GetActiveWorkerCount() int
GetActiveWorkerCount 获取当前存活的 worker 数量
func (*WorkerPool) GetWorkerCount ¶
func (p *WorkerPool) GetWorkerCount() int
GetWorkerCount 获取 worker 数量上限(弹性伸缩的并发安全帽)
func (*WorkerPool) Submit ¶
func (p *WorkerPool) Submit(ctx context.Context, task WorkerTask) error
Submit 提交任务到队列 如果队列满,会阻塞直到有空位或 context 取消
参数:
- ctx: 上下文,用于超时和取消控制
- task: 要执行的任务
返回:
- nil: 任务成功提交
- ErrClosed: Worker 池已关闭
- context.Err(): context 被取消或超时
示例:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := pool.Submit(ctx, func() {
处理任务
})
if err != nil {
log.Errorf("submit failed: %v", err)
}
func (*WorkerPool) SubmitNonBlocking ¶
func (p *WorkerPool) SubmitNonBlocking(task WorkerTask) error
SubmitNonBlocking 非阻塞提交任务 如果队列满,返回错误而不是阻塞
参数:
- task: 要执行的任务
返回:
- nil: 任务成功提交
- ErrClosed: Worker 池已关闭
- ErrQueueFull: 队列已满
示例:
err := pool.SubmitNonBlocking(func() {
处理任务
})
if err == ErrQueueFull {
log.Warn("queue is full, task dropped")
}
func (*WorkerPool) Wait ¶
func (p *WorkerPool) Wait()
Wait 等待所有已提交的任务完成 不关闭 pool,可以继续提交新任务
示例:
pool := NewWorkerPool(20, 100) 提交任务 ... pool.Wait() // 等待所有任务完成 继续提交任务 ...