Kratos 路由與負(fù)載均衡

2022-04-24 15:44 更新

接口實(shí)現(xiàn)

路由與負(fù)載均衡主要的接口是 Selector,在同目錄下也提供了一個(gè)默認(rèn)的 Selector 實(shí)現(xiàn),該實(shí)現(xiàn)可以通過替換 NodeBuilder、Filter、Balancer 來分別實(shí)現(xiàn)節(jié)點(diǎn)權(quán)重計(jì)算算法、服務(wù)路由過濾策略、負(fù)載均衡算法的可插拔

type Selector interface {
  // Selector 內(nèi)部維護(hù)的服務(wù)節(jié)點(diǎn)列表通過 Rebalancer 接口來更新
  Rebalancer

  // Select nodes
  // if err == nil, selected and done must not be empty.
  Select(ctx context.Context, opts ...SelectOption) (selected Node, done DoneFunc, err error)
}

// 通過Rebalancer實(shí)現(xiàn)服務(wù)節(jié)點(diǎn)變更感知
type Rebalancer interface {
  Apply(nodes []Node)
}

已支持的實(shí)現(xiàn):

  • wrr : Weighted round robin (Kratos Client內(nèi)置默認(rèn)算法)
  • p2c : Power of two choices
  • random : Random

使用方式

HTTP Client

import  "github.com/go-kratos/kratos/v2/selector/p2c"
import  "github.com/go-kratos/kratos/v2/selector/filter"

// 創(chuàng)建路由 Filter:篩選版本號(hào)為"2.0.0"的實(shí)例
filter :=  filter.Version("2.0.0")
// 創(chuàng)建 P2C 負(fù)載均衡算法 Selector,并將路由 Filter 注入
selector := p2c.New(p2c.WithFilter(filter))

hConn, err := http.NewClient(
  context.Background(),
  http.WithEndpoint("discovery:///helloworld"),
  http.WithDiscovery(r),
  // 通過 http.WithSelector 將 Selector 注入 HTTP Client 中
  http.WithSelector(
    p2c.New(p2c.WithFilter(filter.Version("2.0.0"))),
  )
)

gRPC Client

import  "github.com/go-kratos/kratos/v2/selector/p2c"
import  "github.com/go-kratos/kratos/v2/selector/filter"

// 創(chuàng)建路由 Filter:篩選版本號(hào)為"2.0.0"的實(shí)例
filter :=  filter.Version("2.0.0")

conn, err := grpc.DialInsecure(
  context.Background(),
  grpc.WithEndpoint("discovery:///helloworld"),
  grpc.WithDiscovery(r),
  // 由于 gRPC 框架的限制,只能使用全局 balancer name 的方式來注入 selector
  grpc.WithBalancerName(wrr.Name),
  // 通過 grpc.WithFilter 注入路由 Filter
  grpc.WithFilter(filter),
)


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)