为单元测试配置RoundRobinLoadBalancer

问题描述 投票:0回答:1

由于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的代码是什么?

java spring-boot configuration spring-cloud ribbon
1个回答
1
投票

我最近也做了同样的切换,离开了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)));
  }
}

请注意,我使用空字符串作为... instanceIdserviceId. 这可能不是最好的做法,但在我的情况下很好。

© www.soinside.com 2019 - 2024. All rights reserved.