Go微服务负载均衡需手动设计客户端路由,核心是维护健康实例列表并按轮询或加权轮询策略选节点;需结合服务发现、线程安全计数、平滑加权及集成HTTP客户端实现。

在 Go 微服务架构中,负载均衡不是靠框架自动完成的,而是需要你主动设计客户端路由逻辑。核心思路是:维护可用服务实例列表,按策略(如轮询、加权轮询)选择一个节点发起请求。下面直接讲实用实现方式,不绕概念。
基础:服务发现 + 实例列表管理
负载均衡的前提是知道有哪些健康实例。通常结合 Consul / Etcd / Nacos 或 DNS-SD 获取服务地址。建议封装一个 ServiceDiscovery 接口:
- 支持定时拉取或监听变更(如 Consul 的 watch)
- 只保留通过健康检查的实例(如 /health 返回 200)
- 缓存实例列表并加读写锁,避免每次选节点都查一次注册中心
示例结构:
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)
}
轮询策略(Round Robin)
最常用,适合实例性能相近的场景。关键点是线程安全的计数器 + 原子操作:
立即学习“go语言免费学习笔记(深入)”;
- 用
atomic.Int64记录当前索引,每次自增后对实例数取模 - 避免多个 goroutine 同时递增导致跳过或重复——原子操作天然解决
- 实例列表更新时,重置计数器(否则可能越界),可用 CAS 或带版本号的 reload
简单实现:
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]
}
加权轮询策略(Weighted Round Robin)
当不同实例 CPU/内存配置不同时,按权重分配流量更合理。注意:不是“每轮按权重发多次”,而是平滑加权(Smooth Weighted RR),避免突发流量打爆高权重点。
- 每个实例维护两个字段:
weight(配置权重)、currentWeight(运行时动态值) - 每次选节点前,所有
currentWeight += weight;选出currentWeight最大的实例;再对该实例currentWeight -= sum(weight) - Golang 中用
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
}
集成到 HTTP 客户端(如 http.RoundTripper)
真正落地时,别每次都手动调 balancer.Next()。推荐包装 http.Transport:
- 自定义
RoundTripper,在RoundTrip(req)中解析req.URL.Host获取服务名 - 查对应 balancer(可 map[string]Balancer 按服务名缓存)
- 拿到实例地址后,改写
req.URL.Host并调用默认 transport 发送 - 失败时可自动重试下一个实例(需控制重试次数,避免雪崩)
这样上层业务代码完全无感:http.Post("http://user-service/v1/profile", ...) 就自动走负载均衡。
基本上就这些。权重和轮询不是非此即彼,生产中常组合使用:先按权重分大流量,再在同权重组内轮询。关键是把实例生命周期、健康状态、并发安全这三块控住,策略本身并不复杂但容易忽略细节。










