fix(loadbalance): 添加 hostnameOnce 确保并发安全

Target 结构体添加 sync.Once 字段,确保 hostname 初始化的并发安全

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
xfy 2026-04-13 16:21:21 +08:00
parent d0396a3854
commit bdf615c585

View File

@ -20,6 +20,7 @@ import (
"hash/fnv"
"net"
"net/url"
"sync"
"sync/atomic"
"time"
)
@ -42,6 +43,7 @@ type Target struct {
resolvedIPs atomic.Pointer[[]string]
URL string
hostname string
hostnameOnce sync.Once
VirtualHashes []uint64
Weight int
Connections int64
@ -373,11 +375,9 @@ func (i *IPHash) SelectExcludingByIP(targets []*Target, excluded []*Target, clie
}
// Hostname 返回目标主机名(从 URL 提取)。
// 如果 hostname 未初始化,会自动调用 initHostname
// 使用 sync.Once 确保线程安全,只初始化一次
func (t *Target) Hostname() string {
if t.hostname == "" {
t.initHostname()
}
t.hostnameOnce.Do(t.initHostname)
return t.hostname
}