Spring webflux:如何配置Controller和WebClient像代理一样工作?

时间:2018-05-30 15:58:59

标签: java spring spring-boot spring-webflux

我需要一个可以在代理模式下工作的端点:将请求转发到外部REST API。 目前我实施了这样的课程,但距离理想还很远。

import java.net.URI;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

@RestController
public class ProxyController2 {

  private static final int OFFSET = 4;
  private static final String SCHEME = "http";
  private static final String HOTS = "127.0.0.1";
  private static final String PORT = "9090";

  @RequestMapping("/proxy/public/**")
  public Mono<String> publicProxy(ServerHttpRequest request) {
    HttpMethod httpMethod = request.getMethod();

    if (bodyRequired(httpMethod)) {
      return WebClient.create()
          .method(httpMethod)
          .uri(composeTargetUri(request))
          .headers(headers -> headers.addAll(request.getHeaders()))
          .body(BodyInserters.fromDataBuffers(request.getBody()))
          .retrieve()
          .bodyToMono(String.class);
    } else {
      return WebClient.create()
          .method(httpMethod)
          .uri(composeTargetUri(request))
          .headers(headers -> headers.addAll(request.getHeaders()))
          .retrieve()
          .bodyToMono(String.class);
    }
  }

  private URI composeTargetUri(ServerHttpRequest request) {
    return UriComponentsBuilder.newInstance()
        .scheme(SCHEME)
        .host(HOTS)
        .port(PORT)
        .path(getTargetPath(request))
        .build()
        .toUri();
  }

  private String getTargetPath(ServerHttpRequest request) {
    return request.getPath().pathWithinApplication()
        .subPath(OFFSET)
        .value();
  }

  private boolean bodyRequired(HttpMethod httpMethod) {
    return httpMethod == HttpMethod.DELETE || httpMethod == HttpMethod.POST
        || httpMethod == HttpMethod.PUT;
  }
}

它有一些缺点:
*它总是以字符串形式返回结果 *我们丢失了回复标题 *我们失去了响应状态(它产生500个错误消息描述)。

您是否知道在spring webflux应用程序中创建代理控制器的好方法?

1 个答案:

答案 0 :(得分:2)

Spring Cloud Gateway

  

构建于Spring Ecosystem之上的API网关,包括:Spring 5,Spring Boot 2和Project Reactor。 Spring Cloud Gateway旨在提供一种简单而有效的方式来路由API,并为他们提供横切关注点,例如:安全性,监控/指标和弹性。

Doc:Spring Cloud Gateway