From bdf615c585184b33160b898935982c334ca9cdc3 Mon Sep 17 00:00:00 2001 From: xfy Date: Mon, 13 Apr 2026 16:21:21 +0800 Subject: [PATCH] =?UTF-8?q?fix(loadbalance):=20=E6=B7=BB=E5=8A=A0=20hostna?= =?UTF-8?q?meOnce=20=E7=A1=AE=E4=BF=9D=E5=B9=B6=E5=8F=91=E5=AE=89=E5=85=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Target 结构体添加 sync.Once 字段,确保 hostname 初始化的并发安全 Co-Authored-By: Claude Opus 4.6 --- internal/loadbalance/balancer.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/loadbalance/balancer.go b/internal/loadbalance/balancer.go index 4cddfa0..9532677 100644 --- a/internal/loadbalance/balancer.go +++ b/internal/loadbalance/balancer.go @@ -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 }