使用Spring Webflux WebClient进行服务发现

时间:2019-01-03 18:23:41

标签: spring spring-boot microservices spring-cloud-netflix reactive

是否可以在Spring webflux Webclient中使用Ribbon和Eureka服务发现?

我尝试了这段代码,但是在集成测试中出现了错误。

reactor.core.Exceptions $ ErrorCallbackNotImplemented:java.lang.IllegalArgumentException:URI不是绝对的:/ auth-service / auth-service / validate-manager-client-access

@Bean
  @LoadBalanced
  public WebClient loadBalancedWebClient() {
    return WebClient.create(baseURL);
  }

  @Override
  public Mono<Boolean> validateManagerClientAccess(Mono<LoginDTO> loginDTOMono) {
    return webClient
        .post()
        .uri(validateManagerURL)
        .body(loginDTOMono, LoginDTO.class)
        .retrieve()
        .bodyToMono(Boolean.class);
  }

# Remote Services Configuration
remote:
  auth-service:
    service-id: auth-service
    path:
      validate-manager-client-access: /auth-service/validate-manager-client-access

1 个答案:

答案 0 :(得分:0)

我自己正在研究……Piotr Minkowski在这里很好地回答了这个问题……

https://dzone.com/articles/reactive-microservices-with-spring-webflux-and-spr

为方便起见,我将最相关的部分发布到此答案。

创建负载平衡的Web客户端构建器

 @Bean
 @LoadBalanced
 public WebClient.Builder loadBalancedWebClientBuilder() {
     return WebClient.builder();
 }

然后可以像

一样使用
@Autowired
private WebClient.Builder webClientBuilder;
@GetMapping("/{id}/with-accounts")
public Mono findByIdWithAccounts(@PathVariable("id") String id) {
    LOGGER.info("findByIdWithAccounts: id={}", id);
    Flux accounts= webClientBuilder.build().get().uri("http://accountservice/customer/{customer}", id).retrieve().bodyToFlux(Account.class);
return accounts
      .collectList()
      .map(a -> new Customer(a))
      .mergeWith(repository.findById(id))
      .collectList()
      .map(CustomerMapper::map);
}