Documentation
¶
Overview ¶
Package loadbalance 提供与具体服务发现实现解耦的负载均衡策略。
本包只依赖一个轻量的 Instance 接口(仅需 GetWeight),不绑定任何特定的 服务实例结构(如 nns/metadata.Instance、httpx.NNSInstance),因此可被 network、nns 等任意上层包复用,是 ekit 负载均衡的唯一算法实现。
支持的策略:
- 轮询(RoundRobin)
- 随机(Random)
- 加权随机(Weighted / WeightedRandom)
使用 New 按策略名创建,或直接调用具体的 NewXxx 构造器。 对于实现 Instance 接口的切片类型,用 ToInstances 转换后即可喂给 Balancer。
Index ¶
Constants ¶
const ( StrategyRoundRobin = "roundrobin" StrategyRandom = "random" StrategyWeighted = "weighted" StrategyWeightedRandom = "weighted_random" )
负载均衡策略名称常量。 这些值与 nns/metadata 中定义的策略字符串保持一致,便于按配置名创建。
Variables ¶
This section is empty.
Functions ¶
func NormalizeStrategy ¶
NormalizeStrategy 将各种别名统一为规范策略名。 规范名以 network/loadbalance 常量为准:
"round_robin" → "roundrobin" "weighted_round_robin" → "weighted" 其他未知名称原样返回
Types ¶
type Instance ¶
type Instance interface {
// GetWeight 返回实例权重,用于加权策略。
GetWeight() float64
}
Instance 负载均衡所需的最小实例抽象。
实现者只需提供 GetWeight 即可参与负载均衡选择。 权重 <= 0 的实例会被策略按权重 1 处理。
func ToInstances ¶
ToInstances 将任意实现 Instance 的具体切片转换为 []Instance。 用于把 []registry.Instance 等具体类型切片喂给 Balancer。
type RoundRobinBalancer ¶
type RoundRobinBalancer struct {
// contains filtered or unexported fields
}
RoundRobinBalancer 轮询负载均衡器。
type WeightedBalancer ¶
type WeightedBalancer struct{}
WeightedBalancer 加权随机负载均衡器。 每次 Pick 按权重概率随机选择实例,非确定性轮询。 如需确定性加权轮询(weight-3 的实例恰好处理 3/4 请求),需自行实现。