fix: prevent reconnect after pool close

This commit is contained in:
MiMoCode
2026-07-10 19:48:06 +08:00
parent fcb4a87be8
commit b7442ab514
2 changed files with 70 additions and 9 deletions
+17
View File
@@ -2,6 +2,7 @@ package db
import (
"context"
"errors"
"fmt"
"log"
"net"
@@ -22,8 +23,11 @@ type Pool struct {
mu sync.RWMutex
conn clickhouse.Conn
healthy bool
closed bool
}
var errPoolClosed = errors.New("db pool is closed")
// NewPool 创建 Pool。即使首次连接失败也返回非 nil 实例,后台会持续重试。
func NewPool(ctx context.Context, dsn string, reconnectInterval time.Duration) *Pool {
p := &Pool{dsn: dsn, reconnectInterval: reconnectInterval}
@@ -35,6 +39,13 @@ func NewPool(ctx context.Context, dsn string, reconnectInterval time.Duration) *
}
func (p *Pool) connect(ctx context.Context) error {
p.mu.RLock()
closed := p.closed
p.mu.RUnlock()
if closed {
return errPoolClosed
}
cctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
opts, err := ClickHouseOptions(p.dsn)
@@ -62,6 +73,11 @@ func (p *Pool) connect(ctx context.Context) error {
return err
}
p.mu.Lock()
if p.closed {
p.mu.Unlock()
_ = conn.Close()
return errPoolClosed
}
if p.conn != nil {
_ = p.conn.Close()
}
@@ -217,6 +233,7 @@ func (p *Pool) Get() clickhouse.Conn {
// Close starts closing the underlying connection and waits within ctx.
func (p *Pool) Close(ctx context.Context) error {
p.mu.Lock()
p.closed = true
conn := p.conn
p.conn = nil
p.healthy = false