由于Ribbon客户端的负载均衡器处于维护模式,我通过设定 spring.cloud.loadbalancer.ribbon.enabled
改为false.使用Ribbon进行客户端测试时,我习惯于用
@Configuration
@Profile("test")
public class ClientTestConfig {
@Bean
public StubServer stubServer() {
return new StubServer().run();
}
@Bean
public ServerList<Server> ribbonServerList() {
return new StaticServerList<>(new Server("localhost", stubServer().getPort()));
}
}
上面的代码相当于RoundRobinLoadBalancer的代码是什么?
我最近也做了同样的切换,离开了Ribbon。在Spring指南中,有一个例子说明了如何配置一个自定义的 ServiceInstanceListSupplier
:https:/spring.ioguidesgsspring-cloud-loadbalancer#_load_balance_across_server_instances。
对于你的情况来说,这可能是这样的。
@Configuration
@Profile("test")
public class ClientTestConfig {
@Bean
public StubServer stubServer() {
return new StubServer().run();
}
@Bean
ServiceInstanceListSupplier serviceInstanceListSupplier() {
return new MyServiceInstanceListSupplier(stubServer().getPort());
}
}
class MyServiceInstanceListSupplier implements ServiceInstanceListSupplier {
private final Integer port;
MyServiceInstanceListSupplier(Integer port) {
this.port = port;
}
@Override
public String getServiceId() {
return "";
}
@Override
public Flux<List<ServiceInstance>> get() {
return Flux.just(Arrays.asList(new DefaultServiceInstance("", "", "localhost", port, false)));
}
}
请注意,我使用空字符串作为... instanceId
和 serviceId
. 这可能不是最好的做法,但在我的情况下很好。