Help us shape the future of Go! Take the 2026 Go Developer Survey

loadbalance

package
v0.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 4 Imported by: 0

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

View Source
const (
	StrategyRoundRobin     = "roundrobin"
	StrategyRandom         = "random"
	StrategyWeighted       = "weighted"
	StrategyWeightedRandom = "weighted_random"
)

负载均衡策略名称常量。 这些值与 nns/metadata 中定义的策略字符串保持一致,便于按配置名创建。

Variables

This section is empty.

Functions

func NormalizeStrategy

func NormalizeStrategy(name string) string

NormalizeStrategy 将各种别名统一为规范策略名。 规范名以 network/loadbalance 常量为准:

"round_robin"           → "roundrobin"
"weighted_round_robin"  → "weighted"
其他未知名称原样返回

Types

type Balancer

type Balancer interface {
	Pick(instances []Instance) (int, error)
}

Balancer 从一组实例中选择一个,返回其索引。

func New

func New(strategy string) (Balancer, error)

New 根据策略名称创建负载均衡器,空字符串或未知策略回退为轮询。 接受规范名或别名(自动标准化)。

type Instance

type Instance interface {
	// GetWeight 返回实例权重,用于加权策略。
	GetWeight() float64
}

Instance 负载均衡所需的最小实例抽象。

实现者只需提供 GetWeight 即可参与负载均衡选择。 权重 <= 0 的实例会被策略按权重 1 处理。

func ToInstances

func ToInstances[T Instance](items []T) []Instance

ToInstances 将任意实现 Instance 的具体切片转换为 []Instance。 用于把 []registry.Instance 等具体类型切片喂给 Balancer。

type RandomBalancer

type RandomBalancer struct{}

RandomBalancer 随机负载均衡器。

func NewRandom

func NewRandom() *RandomBalancer

NewRandom 创建一个新的随机负载均衡器实例。

func (*RandomBalancer) Pick

func (b *RandomBalancer) Pick(instances []Instance) (int, error)

Pick 从实例列表中随机选择一个实例,返回其索引。

type RoundRobinBalancer

type RoundRobinBalancer struct {
	// contains filtered or unexported fields
}

RoundRobinBalancer 轮询负载均衡器。

func NewRoundRobin

func NewRoundRobin() *RoundRobinBalancer

NewRoundRobin 创建一个新的轮询负载均衡器实例。

func (*RoundRobinBalancer) Pick

func (b *RoundRobinBalancer) Pick(instances []Instance) (int, error)

Pick 以轮询方式从实例列表中选择一个实例,返回其索引。

type WeightedBalancer

type WeightedBalancer struct{}

WeightedBalancer 加权随机负载均衡器。 每次 Pick 按权重概率随机选择实例,非确定性轮询。 如需确定性加权轮询(weight-3 的实例恰好处理 3/4 请求),需自行实现。

func NewWeighted

func NewWeighted() *WeightedBalancer

NewWeighted 创建一个新的加权负载均衡器实例。

func (*WeightedBalancer) Pick

func (b *WeightedBalancer) Pick(instances []Instance) (int, error)

Pick 根据实例权重从实例列表中选择一个实例,返回其索引。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL