SpringCloud GateWay 网关 在GlobalFilter 拿出返回数据response

简介: SpringCloud GateWay 网关 在GlobalFilter 拿出返回数据response

前言



文章主旨:   将返回数据拿出来,然后各种处理。


正文


 

先看该篇文章的示例接口:


image.png


红色框框里面就是返回的 response 数据 。


现在我们想要的就是 在返回给到调用方(前端、第三方等)前,我们抓出来数据,随便改一下东西。


例如: 我要把里面的message 提示语改了。


新建一个全局过滤器:


WrapperResponseGlobalFilter.java


import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.charset.Charset;
import java.util.List;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR;
/**
 * @Author JCccc
 * @Description 拦截返回数据, 修改返回数据
 * @Date 2021/8/16 19:22
 */
@Component
public class WrapperResponseGlobalFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(WrapperResponseGlobalFilter.class);
    @Override
    public int getOrder() {
        // -1 is response write filter, must be called before that
        return -2;
    }
    private static Joiner joiner = Joiner.on("");
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator response = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (getStatusCode().equals(HttpStatus.OK) && body instanceof Flux) {
                    // 获取ContentType,判断是否返回JSON格式数据
                    String originalResponseContentType = exchange.getAttribute(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR);
                    if (StringUtils.isNotBlank(originalResponseContentType) && originalResponseContentType.contains("application/json")) {
                        Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                        //(返回数据内如果字符串过大,默认会切割)解决返回体分段传输
                        return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                            List<String> list = Lists.newArrayList();
                            dataBuffers.forEach(dataBuffer -> {
                                try {
                                    byte[] content = new byte[dataBuffer.readableByteCount()];
                                    dataBuffer.read(content);
                                    DataBufferUtils.release(dataBuffer);
                                    list.add(new String(content, "utf-8"));
                                } catch (Exception e) {
                                    log.info("加载Response字节流异常,失败原因:{}", Throwables.getStackTraceAsString(e));
                                }
                            });
                            String responseData = joiner.join(list);
                            System.out.println("responseData:"+responseData);
                            byte[] uppedContent = new String(responseData.getBytes(), Charset.forName("UTF-8")).getBytes();
                            originalResponse.getHeaders().setContentLength(uppedContent.length);
                            return bufferFactory.wrap(uppedContent);
                        }));
                    }
                }
                return super.writeWith(body);
            }
            @Override
            public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
                return writeWith(Flux.from(body).flatMapSequential(p -> p));
            }
        };
        return chain.filter(exchange.mutate().response(response).build());
    }
}


调用接口可以看到,response数据已经被我们拎出来了:


image.png


那么我们简单做个处理,


image.png

    /**
     * 返回数据处理
     *
     * @param responseData
     * @return
     */
    private String responseHandle(String responseData) {
        String responseResultJson = null;
        try {
            JSONObject jsonObject = JSONObject.parseObject(responseData);
            jsonObject.put("message", "JCccc 收藏+关注");
            responseResultJson = jsonObject.toJSONString();
        } catch (Exception e) {
            log.info("返回数据处理转化失败,异常信息={}",e.getMessage());
            return responseData;
        }
        return responseResultJson;
    }


再次请求,可以看到:


返回数据里面的message已经被我们修改成功了


image.png


PS:


还有类似,既然个人信息这么敏感,是不是类似一些接口返回数据需要做统一的加密呢?


如需要,那么也可以通过配置化读取需要加密的ur列表,然后通过exchange把url拿出来做匹对,对responseData  做加密处理。


ServerHttpRequest request = exchange.getRequest();
URI url = request.getURI();
String urlPath = url.getPath();
System.out.println("当前请求url是:"+urlPath);


好了,该篇就到这。

相关文章
|
21天前
|
负载均衡 Nacos 数据安全/隐私保护
SpringCloud GateWay 使用
SpringCloud GateWay 使用
22 0
|
1月前
|
SpringCloudAlibaba Java 网络架构
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(七)Spring Cloud Gateway服务网关
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(七)Spring Cloud Gateway服务网关
108 0
|
6天前
|
监控 Java API
第七章 Spring Cloud 之 GateWay
第七章 Spring Cloud 之 GateWay
11 0
|
22天前
|
JSON 安全 关系型数据库
SpringCloud Gateway 实现自定义全局过滤器 + JWT权限验证
SpringCloud Gateway 实现自定义全局过滤器 + JWT权限验证
|
1月前
|
Java 网络架构 微服务
SpringCloud GateWay网关-学习笔记
SpringCloud GateWay网关-学习笔记
33 0
|
1月前
|
缓存 Java API
【云原生】Spring Cloud Gateway的底层原理与实践方法探究
【云原生】Spring Cloud Gateway的底层原理与实践方法探究
|
2月前
|
监控 Java 应用服务中间件
网关大解密:探索Spring Cloud Alibaba中Gateway的奥秘
网关大解密:探索Spring Cloud Alibaba中Gateway的奥秘
117 1
|
3月前
|
Java Spring
Spring Cloud Alibaba - 26 Gateway-自定义谓词工厂RoutePredicateFactory
Spring Cloud Alibaba - 26 Gateway-自定义谓词工厂RoutePredicateFactory
55 0
|
4月前
|
Java 数据安全/隐私保护 数据格式
Spring Cloud Gateway 网关整合 Knife4j 4.3 实现微服务接口文档聚合
Spring Cloud Gateway 网关整合 Knife4j 4.3 实现微服务接口文档聚合
|
1月前
|
SpringCloudAlibaba 负载均衡 前端开发
【十】SpringCloud Alibaba之整合gateway(包括配置详解以及各种坑)
【十】SpringCloud Alibaba之整合gateway(包括配置详解以及各种坑)
77 2