最近在做网关改造,想要通过Gateway过滤器获取ResponseBody的值,查看了网上的帖子和官网内容:

帖子:https://cloud.tencent.com/developer/article/1384111

官网:https://github.com/spring-cloud/spring-cloud-gateway/blob/master/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/rewrite/ModifyResponseBodyGatewayFilterFactory.java

但在实际操作中却掉坑里了,居然不起作用,就是不进重写但writeWith方法

 @Component
@Order(-2)
public class EncryptResponseBodyFilter implements GlobalFilter { @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) { Flux<? extends DataBuffer> fluxBody = Flux.from(body);
return super.writeWith(fluxBody.map(dataBuffer -> {
// probably should reuse buffers
byte[] content = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(content);
//释放掉内存
DataBufferUtils.release(dataBuffer);
String s = new String(content, Charset.forName("UTF-8"));
//TODO,s就是response的值,想修改、查看就随意而为了
byte[] uppedContent = s.getBytes();
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());
}

后来与帖子和官网代码内容对比,只有Order的方式不同,就换了下实现Ordered重写getOrder方法方式试试,结果出乎意料,居然好用了!!!

真的是绞尽脑汁啊,浪费了不少时间。。。。

后来发现响应数据存在分段响应的问题:

参考:https://blog.csdn.net/fayeyiwang/article/details/9137// JSON响应数据拼接容器

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) {
logger.info("动态加载API加密规则失败,失败原因:{}", Throwables.getStackTraceAsString(e));
}
});
String responseData = joiner.join(list);
// 二次处理(加密/过滤等)如果不需要做二次处理可直接跳过下行
responseData = beforeBodyWriteInternal(responseData, exchange.getRequest());
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());
}

获取SpringCloud gateway响应的response的值,记录踩坑的更多相关文章

  1. Local Response Normalization作用——对局部神经元的活动创建竞争机制,使得其中响应比较大的值变得相对更大,并抑制其他反馈较小的神经元,增强了模型的泛化能力

    AlexNet将LeNet的思想发扬光大,把CNN的基本原理应用到了很深很宽的网络中.AlexNet主要使用到的新技术点如下. (1)成功使用ReLU作为CNN的激活函数,并验证其效果在较深的网络超过 ...

  2. 拦截器HandlerInterceptorAdapter的postHandle和afterCompletion无法获取response返回值问题

    缘起 有一个需求,在进入controller之前验证调用次数是否超过限制,在响应之后判断是否正常返回,对调用次数进行+1,发现带@RestController的类和带@ResponseBody的方法在 ...

  3. SpringCloud gateway (史上最全)

    疯狂创客圈 Java 分布式聊天室[ 亿级流量]实战系列之 -25[ 博客园 总入口 ] 前言 ### 前言 疯狂创客圈(笔者尼恩创建的高并发研习社群)Springcloud 高并发系列文章,将为大家 ...

  4. SpringCloud gateway 3

    参考博客:https://www.cnblogs.com/crazymakercircle/p/11704077.html 1.1 SpringCloud Gateway 简介 SpringCloud ...

  5. SpringCloud Gateway 测试问题解决

    本文针对于测试环境SpringCloud Gateway问题解决. 1.背景介绍 本文遇到的问题都是在测试环境真正遇到的问题,不一定试用于所有人,仅做一次记录,便于遇到同样问题的干掉这些问题. 使用版 ...

  6. SpringCloud请求响应数据转换(二)

    上篇文章记录了从后端接口返回数据经过切面和消息转换器处理后返回给前端的过程.接下来,记录从请求发出后到后端接口调用过的过程. web请求处理流程 源码分析 ApplicationFilterChain ...

  7. 万字长文:SpringCloud gateway入门学习&实践

    官方文档:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/# ...

  8. SpringCloud Gateway微服务网关实战与源码分析-上

    概述 定义 Spring Cloud Gateway 官网地址 https://spring.io/projects/spring-cloud-gateway/ 最新版本3.1.3 Spring Cl ...

  9. 转:PHP--获取响应头(Response Header)方法

    转:http://blog.sina.com.cn/s/blog_5f54f0be0102uvxu.html PHP--获取响应头(Response Header)方法 方法一: ========== ...

随机推荐

  1. JavaScript 语句解析

    在 HTML 中,JavaScript 语句是由 web 浏览器“执行”的“指令”. 实例 var x, y, z; // 语句 1 x = 22; // 语句 2 y = 11; // 语句 3 z ...

  2. Shadow Map -- 点阴影(全方位)

    昨晚终于把点阴影(深度CubeMap)程序调通了,思想不难,基本就是在上节定向光阴影基础上稍作修改,但是CG程序不太方便Debug,需要输出中间效果图进行判断,耽搁了一会儿. 过程如下: 1.将深度渲 ...

  3. 基于阿里云平台的使用python脚本发送短信

    第一步:点击短信服务下的帮助文档 第二步:安装python的SDK:点击安装python sdk 第三步:直接通过python的pip工具安装即可,方便快捷: 第四步:点击红框进行测试: 第五步:测试 ...

  4. mysql导出数据的几种形式-待更新

    1.导出某个数据库的某张表,添加where条件 mysqldump -u [用户名] -p  -h [ip地址]  --default-character-set=utf8 [数据库名] [表名] - ...

  5. win7+vim搭建+verilog HDL IDE

    参考地址:http://www.huangdc.com/421 参考文章为2016年,部分更新贴于文章内了 安装下载vim vim在win下叫gvim,下载地址:https://www.vim.org ...

  6. Windows下同时安装python2和python3如何兼容版本

    引言:因学习需要把python2和python3都安装了,为了避免使用过程中混淆版本在网上找了一些解决方案,亲测可用.方法如下: 分别下载并安装Python2.x和Python3.x. 配置环境变量. ...

  7. Paper | LISTEN, ATTEND AND SPELL: A NEURAL NETWORK FOR LARGE VOCABULARY CONVERSATIONAL SPEECH RECOGNITION

    目录 1. 相关工作 2. 方法细节 2.1 收听器 2.2 注意力和拼写 本文提出了一个基于神经网络的语音识别系统List, Attend and Spell(LAS),能够将语音直接转录为文字. ...

  8. 《细说PHP》第四版 样章 第23章 自定义PHP接口规范 10

    23.5.4  客户端访问API 按RESTful规范开发API,又有详细的帮助文档,客户端的应用就相对容易一些.下面,以PHP作为访问接口的客户端,演示API的应用.在PHP中请求接口需要使用CUR ...

  9. linux的vi编辑器常用用法一览

    vi 命令用于编辑文本文件,语法: vi 文件名 vi 是一个比较强大的编辑工具,类似于windows下的notepad,但是功能要强大的多.vi分为三种模式,分别是“一般模式”,“编辑模式”,“命令 ...

  10. Java设计模式:Abstract Factory(抽象工厂)模式

    概念定义 抽象工厂(Abstract Factory)模式提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类. 抽象工厂模式中,系统的产品有多于一个的产品族(一个产品族里定义多个产品) ...