Go微服务负载均衡需手动设计客户端路由,核心是维护健康实例列表并按轮询或加权轮询策略选节点;需结合服务发现、线程安全计数、平滑加权及集成HTTP客户端实现。
在 Go 微服务
架构中,负载均衡不是靠框架自动完成的,而是需要你主动设计客户端路由逻辑。核心思路是:维护可用服务实例列表,按策略(如轮询、加权轮询)选择一个节点发起请求。下面直接讲实用实现方式,不绕概念。
负载均衡的前提是知道有哪些健康实例。通常结合 Consul / Etcd / Nacos 或 DNS-SD 获取服务地址。建议封装一个 ServiceDiscovery 接口:
示例结构:
type Instance struct {
ID string
Addr string // e.g. "10.0.1.12:8080"
Weight int // 权重,默认 1
Metadata map[string]string
}
type ServiceDiscovery interface {
GetInstances(serviceName string) ([]Instance, error)
}
最常用,适合实例性能相近的场景。关键点是线程安全的计数器 + 原子操作:
atomic.Int64 记录当前索引,每次自增后对实例数取模简单实现:
type RoundRobinBalancer struct {
instances atomic.Value // []Instance
counter atomic.Int64
}
func (b *RoundRobinBalancer) Next() *Instance {
insts := b.instances.Load().([]Instance)
if len(insts) == 0 {
return nil
}
idx := b.counter.Add(1) % int64(len(insts))
return &insts[idx]
}
当不同实例 CPU/内存配置不同时,按权重分配流量更合理。注意:不是“每轮按权重发多次”,而是平滑加权(Smooth Weighted RR),避免突发流量打爆高权重点。
weight(配置权重)、currentWeight(运行时动态值)currentWeight += weight;选出 currentWeight 最大的实例;再对该实例 currentWeight -= sum(weight)
sync.RWMutex 保护实例切片和 currentWeight 字段示例片段:
type WeightedInstance struct {
Instance
currentWeight int
}
func (b *WeightedRR) Next() *Instance {
b.mu.RLock()
defer b.mu.RUnlock()
total := 0
for i := range b.instances {
b.instances[i].currentWeight += b.instances[i].Weight
total += b.instances[i].Weight
}
var chosen *WeightedInstance
for i := range b.instances {
if chosen == nil || b.instances[i].currentWeight > chosen.currentWeight {
chosen = &b.instances[i]
}
}
if chosen != nil {
chosen.currentWeight -= total
return &chosen.Instance
}
return nil
}
真正落地时,别每次都手动调 balancer.Next()。推荐包装 http.Transport:
RoundTripper,在 RoundTrip(req) 中解析 req.URL.Host 获取服务名req.URL.Host 并调用默认 transport 发送这样上层业务代码完全无感:http.Post("http://user-service/v1/profile", ...) 就自动走负载均衡。
基本上就这些。权重和轮询不是非此即彼,生产中常组合使用:先按权重分大流量,再在同权重组内轮询。关键是把实例生命周期、健康状态、并发安全这三块控住,策略本身并不复杂但容易忽略细节。