Routing and Load Balancing

Interface Implementation

The main interface for routing and load balancing is Selector, and a default Selector implementation is also provided in the same directory. This implementation can implement node weight calculation algorithm, service routing filtering strategy, and load balancing algorithm by replacing NodeBuilder, Filter, Balancer, and Pluggable.

  1. type Selector interface {
  2. // The list of service nodes maintained internally by the Selector is updated through the Rebalancer interface.
  3. Rebalancer
  4. // Select nodes
  5. // if err == nil, selected and done must not be empty.
  6. Select(ctx context.Context, opts ...SelectOption) (selected Node, done DoneFunc, err error)
  7. }
  8. // Realize service node change awareness through Rebalancer.
  9. type Rebalancer interface {
  10. Apply(nodes []Node)
  11. }

Supported implementations:

  • wrr : Weighted round robin (Kratos Client built-in default algorithm)
  • p2c : Power of two choices
  • random : Random

How to use

HTTP Client

  1. import "github.com/go-kratos/kratos/v2/selector/wrr"
  2. import "github.com/go-kratos/kratos/v2/selector/filter"
  3. // Create a route Filter: filter instances with version number "2.0.0".
  4. filter := filter.Version("2.0.0")
  5. // Create P2C load balancing algorithm Selector, and inject routing Filter.
  6. selector.SetGlobalSelector(wrr.NewBuilder())
  7. hConn, err := http.NewClient(
  8. http.WithEndpoint("discovery:///helloworld"),
  9. http.WithDiscovery(r),
  10. http.WithNodeFilter(filter)
  11. )

gRPC Client

  1. import "github.com/go-kratos/kratos/v2/selector/wrr"
  2. import "github.com/go-kratos/kratos/v2/selector/filter"
  3. // Create a route Filter: filter instances with version number "2.0.0".
  4. filter := filter.Version("2.0.0")
  5. // Due to the limitations of the gRPC framework, only the global balancer name can be used to inject Selector.
  6. selector.SetGlobalSelector(wrr.NewBuilder())
  7. conn, err := grpc.DialInsecure(
  8. context.Background(),
  9. grpc.WithEndpoint("discovery:///helloworld"),
  10. grpc.WithDiscovery(r),
  11. // Inject routing Filter through grpc.WithFilter.
  12. grpc.WithNodeFilter(filter),
  13. )