【问题标题】:Using Spring Boot 2 WebClient, in threadsafe / per-request manner, how send diff headers every request?使用 Spring Boot 2 WebClient,以线程安全/每个请求的方式,如何发送每个请求的差异标头?
【发布时间】:2019-07-14 19:27:44
【问题描述】:

在 Spring Boot 1.5.x 中,我可以使用带有 AsyncRestTemplate 的拦截器从传入请求中获取标头到 RestController 端点,并将它们放入通过 AsyncRestTemplate 发出的任何 exchange 请求中。

我不明白这如何与WebClient 一起工作。如果您构建一个WebClient,它的所有标题等都已设置且不可更改:

WebClient client = WebClient.builder()
    .baseUrl( "http://blah.com" )
    .defaultHeader( "Authorization", "Bearer ey..." )
    .build();

虽然我可以使用client.mutate() 更改这些,但它会实例化一个全新的 WebClient 对象。我不想在每个请求上都创建一个新的。有没有办法保留WebClient 并拥有每个请求的标头和其他参数?

每次都强制创建一个新对象似乎是一种很大的浪费和糟糕的性能。

【问题讨论】:

    标签: java spring-boot spring-webflux


    【解决方案1】:

    您在此处使用的是默认标头,应为此 WebClient 实例发送的所有请求发送默认标头。所以这对于通用标题很有用。

    您当然可以像这样根据每个请求更改请求标头:

    Mono<String> result = this.webClient.get()
          .uri("/greeting")
          .header("Something", "value")
          .retrieve().bodyToMono(String.class);
    

    如果您希望有一个类似拦截器的机制在发送请求之前对其进行变异,您可以使用过滤器配置WebClient 实例:

    WebClient
        .builder()
        .filter((request, next) -> {
                // you can mutate the request before sending it
                ClientRequest newRequest = ClientRequest.from(request)
                        .header("Something", "value").build();
                return next.exchange(newRequest);
    })
    

    请查看the Spring Framework documentation about WebClient

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 2022-01-18
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      相关资源
      最近更新 更多