refactor: 将 Pool 重构为接口,提取 pool 为具体实现
This commit is contained in:
24
pool.go
24
pool.go
@@ -72,8 +72,16 @@ func WithStderr(w io.Writer) Option {
|
||||
return func(c *poolConfig) { c.stderr = w }
|
||||
}
|
||||
|
||||
// Pool 管理多个 Python worker 进程及其连接池
|
||||
type Pool struct {
|
||||
// Pool 是 Python worker 进程池的接口
|
||||
type Pool interface {
|
||||
// Close 关闭所有 worker 进程和连接
|
||||
Close()
|
||||
acquire(ctx context.Context) (net.Conn, *worker, error)
|
||||
nextReqID() uint64
|
||||
}
|
||||
|
||||
// pool 是 Pool 的具体实现
|
||||
type pool struct {
|
||||
workers []*worker
|
||||
idx atomic.Uint64
|
||||
reqID atomic.Uint64
|
||||
@@ -88,7 +96,7 @@ type Pool struct {
|
||||
// gobridge.WithScriptArgs("worker.py"),
|
||||
// gobridge.WithWorkDir("./worker"),
|
||||
// )
|
||||
func NewPool(script string, opts ...Option) (*Pool, error) {
|
||||
func NewPool(script string, opts ...Option) (Pool, error) {
|
||||
cfg := &poolConfig{
|
||||
workers: 2,
|
||||
maxConnsPerWorker: 4,
|
||||
@@ -114,19 +122,23 @@ func NewPool(script string, opts ...Option) (*Pool, error) {
|
||||
}
|
||||
workers[i] = w
|
||||
}
|
||||
return &Pool{workers: workers}, nil
|
||||
return &pool{workers: workers}, nil
|
||||
}
|
||||
|
||||
// acquire 以轮询方式从进程池取出一个可用连接
|
||||
func (p *Pool) acquire(ctx context.Context) (net.Conn, *worker, error) {
|
||||
func (p *pool) acquire(ctx context.Context) (net.Conn, *worker, error) {
|
||||
idx := p.idx.Add(1) % uint64(len(p.workers))
|
||||
w := p.workers[idx]
|
||||
conn, err := w.acquire(ctx)
|
||||
return conn, w, err
|
||||
}
|
||||
|
||||
func (p *pool) nextReqID() uint64 {
|
||||
return p.reqID.Add(1)
|
||||
}
|
||||
|
||||
// Close 关闭所有 worker 进程和连接
|
||||
func (p *Pool) Close() {
|
||||
func (p *pool) Close() {
|
||||
for _, w := range p.workers {
|
||||
w.stop()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user