协程池单例模式

This commit is contained in:
Cold
2025-12-06 12:02:34 +08:00
committed by 张斌
parent 86661c687a
commit f7cb007491
2 changed files with 50 additions and 26 deletions

View File

@@ -2,6 +2,7 @@ package ragflow
import (
"context"
"sync"
"gitee.com/red-future---jilin-g/common/redis"
"github.com/gogf/gf/v2/errors/gerror"
@@ -15,24 +16,44 @@ type WorkerPool struct {
size int
}
// NewWorkerPool 创建协程池
// 单例模式相关变量
var (
workerPoolInstance *WorkerPool
workerPoolOnce sync.Once
)
// GetWorkerPoolWithSize 获取指定大小的协程池单例
// 使用 sync.Once 确保只创建一次size 仅首次调用生效
func GetWorkerPoolWithSize(size int) *WorkerPool {
workerPoolOnce.Do(func() {
if size <= 0 {
size = 200 // 默认大小
}
workerPoolInstance = &WorkerPool{
pool: grpool.New(size),
size: size,
}
})
return workerPoolInstance
}
// GetWorkerPool 获取协程池单例(使用默认大小 200
func GetWorkerPool() *WorkerPool {
return GetWorkerPoolWithSize(200)
}
// NewWorkerPool 创建协程池(兼容旧代码,内部使用单例)
// 参数:
// - size: 协程池大小,建议设置为 CPU 核心数的 2-4 倍
// - size: 协程池大小,仅首次调用生效
//
// 返回:
// - *WorkerPool: 协程池实例
// - *WorkerPool: 协程池单例实例
// - error: 创建失败时返回错误
func NewWorkerPool(size int) (*WorkerPool, error) {
if size <= 0 {
return nil, gerror.New("协程池大小必须大于0")
}
pool := grpool.New(size)
return &WorkerPool{
pool: pool,
size: size,
}, nil
return GetWorkerPoolWithSize(size), nil
}
// Submit 提交任务到协程池