当前位置: 首页 > news >正文

SpringCloud-Gateway修改Response响应体,并解决大数据量返回不全等问题

官网相关案例:

Spring Cloud Gatewayicon-default.png?t=N7T8https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#the-modifyresponsebody-gatewayfilter-factory

ModifyRequestBodyGatewayFilterFactory类:

https://github.com/spring-cloud/spring-cloud-gateway/blob/3.1.x/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/factory/rewrite/ModifyResponseBodyGatewayFilterFactory.javaicon-default.png?t=N7T8https://github.com/spring-cloud/spring-cloud-gateway/blob/3.1.x/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/factory/rewrite/ModifyResponseBodyGatewayFilterFactory.java

相关代码:

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
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.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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.util.List;/*** @Author: meng* @Description: 自定义返回体 - 借鉴原生类ModifyRequestBodyGatewayFilterFactory实现* https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#the* -modifyresponsebody-gatewayfilter-factory* @Date: 2023/4/18 13:37* @Version: 1.0*/
@Slf4j
@Component
public class ResponseGatewayFilterFactory extends AbstractGatewayFilterFactory<ResponseGatewayFilterFactory.Config> {public ResponseGatewayFilterFactory() {super(Config.class);}@Data@AllArgsConstructor@NoArgsConstructorpublic static class Config {// 不需要自定义的接口List<String> pathExclude;}@Overridepublic GatewayFilter apply(Config config) {RewriteResponseGatewayFilter rewriteResponseGatewayFilter = new RewriteResponseGatewayFilter(config);return rewriteResponseGatewayFilter;}public class RewriteResponseGatewayFilter implements GatewayFilter, Ordered {private Config config;public RewriteResponseGatewayFilter(Config config) {this.config = config;}@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {// 不需要自定义的接口,直接返回log.info("pathExclude:{}", config.pathExclude);if (CollUtil.isNotEmpty(config.pathExclude)) {long count = config.pathExclude.stream().filter(uri -> StrUtil.contains(exchange.getRequest().getPath().toString(), uri)).count();if (count > 0) {return chain.filter(exchange);}}String appId = exchange.getRequest().getHeaders().getFirst("X-APPID");if (StrUtil.isBlank(appId)) {return buildResponse(exchange, HttpStatus.UNAUTHORIZED.value(), "appId不能为空");}ServerHttpResponse originalResponse = exchange.getResponse();DataBufferFactory bufferFactory = originalResponse.bufferFactory();try {ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {@Overridepublic Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {if (body instanceof Flux) {Flux<? extends DataBuffer> fluxBody = Flux.from(body);return super.writeWith(fluxBody.buffer().map(dataBuffers -> {byte[] newContent = new byte[0];try {DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();DataBuffer join = dataBufferFactory.join(dataBuffers);byte[] content = new byte[join.readableByteCount()];join.read(content);DataBufferUtils.release(join);// 获取响应数据String responseStr = new String(content, "UTF-8");// 修改响应数据JSONObject jsonObject = new JSONObject();jsonObject.put("code", HttpStatus.UNAUTHORIZED.value());jsonObject.put("message", "请求成功");jsonObject.put("data", responseStr);String message = jsonObject.toJSONString();newContent = message.getBytes("UTF-8");originalResponse.getHeaders().setContentLength(newContent.length);}catch (Exception e) {log.error("appId:{}, responseStr exchange error:{}", appId, e);throw new RuntimeException(e);}return bufferFactory.wrap(newContent);}));}return super.writeWith(body);}@Overridepublic Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {return writeWith(Flux.from(body).flatMapSequential(p -> p));}};return chain.filter(exchange.mutate().response(decoratedResponse).build());}catch (Exception e) {log.error("RewriteResponse error:{}", e);return Mono.error(new Exception("RewriteResponse fail", e));}}@Overridepublic int getOrder() {return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 2;}}@SneakyThrowspublic static Mono<Void> buildResponse(ServerWebExchange exchange, int code, String message) {ServerHttpResponse response = exchange.getResponse();response.setStatusCode(HttpStatus.OK);response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);JSONObject jsonObject = new JSONObject();jsonObject.put("code", code);jsonObject.put("message", message);jsonObject.put("data", "");byte[] bytes = jsonObject.toJSONString().getBytes("UTF-8");DataBuffer bodyDataBuffer = response.bufferFactory().wrap(bytes);return response.writeWith(Mono.just(bodyDataBuffer));}}

http://www.lryc.cn/news/232596.html

相关文章:

  • Spark与SQL之间NB的转换_withClumn,split及SubString
  • 修改服务器端Apache默认根目录
  • 网络安全(大厂面试真题集)
  • 系列五、JVM的内存结构【PC寄存器】
  • ClickHouse UDF 运行速度慢问题
  • python科研绘图:面积图
  • SQL基础理论篇(六):多表的连接方式
  • 七、Nacos和Eureka的区别
  • Web前端—小兔鲜儿电商网站底部设计及网站中间过渡部分设计
  • 树莓派通过网线连接电脑(校园网也能连接),实现SSH连接
  • asp.net core EF Sqlserver
  • sqlserver 删除master数据库特定前缀开头的所有表的sql语句
  • 【计算机网络】P2 性能指标
  • SDL音视频渲染
  • 2311rust到27版本更新
  • 网络运维Day18
  • leetcode刷题日志-13整数转罗马数字
  • docker 部署mysql主从复制
  • C++打怪升级(十一)- STL之list
  • Python编程陷阱(七)
  • Python如何调用ixchariot进行吞吐量测试
  • 51单片机应用从零开始(五)·加减乘除运算
  • Meta降本增效大招之:弃用产品
  • Adobe Illustrator——原创设计的宝藏软件
  • LEEDCODE 220 存在重复元素3
  • 从内网到公网:使用Axure RP和内网穿透技术发布静态web页面的完整指南
  • 第三天课程 RabbitMQ
  • Ubuntu18.04编译OpenCV时遇到无法下载ADE的问题
  • 基于JavaWeb+SSM+社区居家养老服务平台—颐养者端微信小程序系统的设计和实现
  • 算法实战:亲自写红黑树之五 删除erase的平衡