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

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
	@NoArgsConstructor
	public static class Config {
 
		// 不需要自定义的接口
		List<String> pathExclude;
 
	}
 
	@Override
	public 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;
		}
 
		@Override
		public 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) {
					@Override
					public 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);
					}
 
					@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(decoratedResponse).build());
			}
			catch (Exception e) {
				log.error("RewriteResponse error:{}", e);
				return Mono.error(new Exception("RewriteResponse fail", e));
			}
		}
 
		@Override
		public int getOrder() {
			return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 2;
		}
 
	}
 
	@SneakyThrows
	public 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.kler.cn/a/134493.html

相关文章:

  • 大数据 ETL + Flume 数据清洗 — 详细教程及实例(附常见问题及解决方案)
  • 少儿学习Scratch编程的好处和坏处
  • 单例模式详解:如何优雅地实现线程安全的单例
  • 【项目开发 | 跨域认证】JSON Web Token(JWT)
  • Qwen2 系列大型语言模型
  • 【时间之外】IT人求职和创业应知【34】-人和机器人,机器人更可靠
  • 关于ASO优化的分步入门指南2
  • 生成对抗网络Generative Adversarial Network,GAN
  • 【前沿学习】美国零信任架构发展现状与趋势研究
  • TypeError 异常详细解析
  • Java-拼图小游戏
  • 6.2 List和Set接口
  • 力扣hot100 两数之和 哈希表
  • unexpected end of stream on
  • vue3按需引入 vite-plugin-style-import 2.0版本报错(解决办法)
  • 软件测试/测试开发/人工智能丨视觉与图像识别自动化测试
  • JAXB:用XmlElement注解复杂类型的Java属性,来产生多层嵌套的xml元素
  • 基于C++实现循环赛日程表(分治算法)
  • 导向矢量(Steering Vector)和束波权重
  • Linux(2):初探
  • APP外包开发需要注意的问题
  • 二十三种设计模式:解密职责链模式-购物优惠活动的设计艺术
  • KVM网络环境下vlan和trunk的理解
  • Angular菜单项激活状态保持
  • milvus数据管理-压缩数据
  • Python 如何实现职责链设计模式?什么是职责链设计模式?Python 职责链设计模式示例代码