【问题标题】:Spring webflux webfilter forward request external applicationspring webflux webfilter转发请求外部应用
【发布时间】:2021-10-26 05:46:56
【问题描述】:

我正在开发 springboot webflux 应用程序。我想过滤对我的应用程序的传入请求,并基于一些逻辑我想将请求转发到另一个应用程序(仅来自服务器),其中包含所有标头和请求有效负载。

我已经尝试过 response.getHeaders().setLocation(mutatedURL)。但这将是基于客户端的重定向,不是必需的。

【问题讨论】:

  • 这就是 301 的重点,您是在告诉您的客户该去哪里。
  • @VovaBilyachat:你是对的。用要求更新了问题。
  • 您有机会查看我的答案吗:?

标签: spring-webflux spring-cloud-gateway


【解决方案1】:

如果我理解正确,您想要做的是,如果请求进来,您正在检查某些事情并根据您允许继续的某些规则,或者您调用一些外部 URL 并将结果返回给客户端

package com.vob.webflux.webfilter.filter;

import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class ProxyFilter implements WebFilter {

    private final WebClient webClient;

    public ProxyFilter() {
        this.webClient = WebClient.create("https://stackoverflow.com");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        var goToOtherAddress = false; // replace this to be your logic which will determine where request go
        return goToOtherAddress
                ? requestOtherWebsite(exchange.getRequest()).flatMap(body -> writeResponse(exchange, body)) // this will return result from external server
                : chain.filter(exchange); // This will allow request to reach your controller
    }

    public Mono<String> requestOtherWebsite(ServerHttpRequest request) {
        return this.webClient.get().uri("/someurlhere")
                .headers(httpHeaders -> {

                    for (var header : request.getHeaders().entrySet()) {
                        // TODO make it how you want
                        httpHeaders.set(header.getKey(), header.getValue().get(0));
                    }
                })
                .retrieve()
                .bodyToMono(String.class);
    }


    private Mono<Void> writeResponse(ServerWebExchange exchange, String message) {
        exchange.getResponse().setRawStatusCode(HttpStatus.OK.value());
        exchange.getResponse().getHeaders().add("Content-Type", "application/json");
        return exchange
                .getResponse()
                .writeWith(
                        Flux.just(
                                exchange.getResponse().bufferFactory().wrap(message.getBytes(StandardCharsets.UTF_8))));
    }
}

【讨论】:

  • 我使用spring cloud gateway route解决了这个问题
猜你喜欢
  • 2018-07-05
  • 2019-03-11
  • 2018-04-05
  • 2022-01-11
  • 2020-07-24
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 2021-07-27
相关资源
最近更新 更多