阅读(1096) (0)

Micronaut 客户端负载均衡

2023-02-23 13:41:55 更新

当从 Consul、Eureka 或其他服务发现服务器发现服务时,DiscoveryClient 会发出可用 ServiceInstance 的列表。

默认情况下,Micronaut 使用此列表中的服务器自动执行 Round Robin 客户端负载平衡。这与重试建议相结合,为您的微服务基础设施增加了额外的弹性。

负载平衡由 LoadBalancer 接口处理,该接口有一个 LoadBalancer.select() 方法,该方法返回一个发出 ServiceInstance 的 Publisher。

返回 Publisher 是因为选择 ServiceInstance 的过程可能会导致网络操作,具体取决于所采用的服务发现策略。

LoadBalancer 接口的默认实现是 DiscoveryClientRoundRobinLoadBalancer。您可以用另一种实现替换此策略,以自定义在 Micronaut 中处理客户端负载平衡的方式,因为有许多不同的方法可以优化负载平衡。

例如,您可能希望在特定区域中的服务之间进行负载平衡,或者在具有最佳总体响应时间的服务器之间进行负载平衡。

要替换 LoadBalancer,请定义一个替换 DiscoveryClientLoadBalancerFactory 的 bean。

事实上,这正是 Netflix Ribbon 支持所做的,在下一节中描述。

Netflix Ribbon 支持

使用 CLI

如果您使用 Micronaut CLI 创建项目,请提供 netflix-ribbon 功能以在您的项目中配置 Netflix 功能区:

$ mn create-app my-app --features netflix-ribbon

Netflix Ribbon 是 Netflix 使用的进程间通信库,支持可定制的负载平衡策略。

如果您的应用程序执行客户端负载平衡的方式需要更大的灵活性,您可以使用 Micronaut 的 Netflix Ribbon 支持。

要将功能区支持添加到您的应用程序,请将 netflix-ribbon 配置添加到您的构建中:

 Gradle Maven 
implementation("io.micronaut.netflix:micronaut-netflix-ribbon")
<dependency>
    <groupId>io.micronaut.netflix</groupId>
    <artifactId>micronaut-netflix-ribbon</artifactId>
</dependency>

LoadBalancer 实现现在将是 RibbonLoadBalancer 实例。

可以使用配置中的功能区命名空间设置功能区的配置选项。例如在您的配置文件中(例如 application.yml):

Configuring Ribbon

 Properties Yaml  Toml  Groovy  Hocon  JSON 
ribbon.VipAddress=test
ribbon.ServerListRefreshInterval=2000
ribbon:
  VipAddress: test
  ServerListRefreshInterval: 2000
[ribbon]
  VipAddress="test"
  ServerListRefreshInterval=2000
ribbon {
  VipAddress = "test"
  ServerListRefreshInterval = 2000
}
{
  ribbon {
    VipAddress = "test"
    ServerListRefreshInterval = 2000
  }
}
{
  "ribbon": {
    "VipAddress": "test",
    "ServerListRefreshInterval": 2000
  }
}

每个发现的客户端也可以在 ribbon.clients 下配置。例如给定一个 @Client(id = "hello-world") 你可以配置 Ribbon 设置:

Per Client Ribbon Settings

 Properties Yaml  Toml  Groovy  Hocon  JSON 
ribbon.clients.hello-world.VipAddress=test
ribbon.clients.hello-world.ServerListRefreshInterval=2000
ribbon:
  clients:
    hello-world:
      VipAddress: test
      ServerListRefreshInterval: 2000
[ribbon]
  [ribbon.clients]
    [ribbon.clients.hello-world]
      VipAddress="test"
      ServerListRefreshInterval=2000
ribbon {
  clients {
    helloWorld {
      VipAddress = "test"
      ServerListRefreshInterval = 2000
    }
  }
}
{
  ribbon {
    clients {
      hello-world {
        VipAddress = "test"
        ServerListRefreshInterval = 2000
      }
    }
  }
}
{
  "ribbon": {
    "clients": {
      "hello-world": {
        "VipAddress": "test",
        "ServerListRefreshInterval": 2000
      }
    }
  }
}

默认情况下,Micronaut 为每个将 Ribbon 与 Micronaut 的 DiscoveryClient 集成的客户端注册一个 DiscoveryClientServerList。