java Spring云网关自定义网关过滤器,用于请求和响应的访问和修改

crcmnpdw  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(76)

如何使用自定义网关过滤器访问和修改Spring Cloud Gateway中的请求和响应?
我想把一个REST请求转换成SOAP并发出一个调用,在收到SOAP响应后我想把SOAP响应转换成REST响应并使用自定义网关过滤器发回

42fyovps

42fyovps1#

@Component
public class MyGlobalFilter implements GlobalFilter{

    @Autowired
    WebClient.Builder builder;

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpResponse response = exchange.getResponse();
    return getFromSoap(response).switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
            .flatMap(dataBuffer -> response.writeWith(Mono.just(dataBuffer)));
}

private Mono<DataBuffer> getFromSoap(ServerHttpResponse response) {
    response.setStatusCode(HttpStatus.OK);
    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    return builder.build().get().uri("http://127.0.0.1:8080/test/list?query=11").retrieve().bodyToMono(RestResp.class).flatMap(result -> {
        if(result.isFailed()){
            return Mono.empty();
        }
        String data = JacksonUtils.toJson(result);
        return Mono.just(response.bufferFactory().wrap(data.getBytes(StandardCharsets.UTF_8)));
    });
}

}

相关问题