背景
使用Spring Cloud Gateway作为网关时经常会需要对报文内的json数据进行修改,但是目前看到的实现方法看起来都很复杂,这里提供一种使用Spring官方提供的ModifyRequestBodyGatewayFilterFactory类来修改json报文的方法
依赖
- Spring Boot版本:2.7.15
- Hutool: 5.8.21
- Java: 11
实现逻辑
实现分为两个部分
- filter:在自定义的filter内注入ModifyRequestBodyGatewayFilterFactory类,然后调用,该类会自动完成对修改结果的重新包装。
- service: 自定义的service实现ModifyRequestBodyGatewayFilterFactory类的RewriteFunction接口完成对json数据的处理
自定义filter
@Component
@Slf4j
public class RequestModifyFilter implements GlobalFilter, Ordered {
@Autowired
private ModifyRequestBodyGatewayFilterFactory modifyRequestBodyFilter;
@Autowired
private JsonRequestBodyRewriteService jsonRequestBodyRewriteService;
@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
MediaType mediaType = exchange.getRequest().getHeaders().getContentType();
if (MediaType.APPLICATION_json.isCompatibleWith(mediaType)) {
// 纯json报文处理逻辑
return modifyRequestBodyFilter
.apply(
new ModifyRequestBodyGatewayFilterFactory.Config()
.setRewriteFunction(byte[].class, byte[].class, jsonRequestBodyRewriteService))
.filter(exchange, chain);
} else {
return filter(exchange, chain);
}
}
@Override
public int getOrder() {
return OrderConstant.REQUEST_MODIFY_FILTER.getOrder();
}
}
自定义service
@Service
@Slf4j
public class JsonRequestBodyRewriteService implements RewriteFunction {
@Override
public Publisher apply(ServerWebExchange exchange, byte[] body) {
jsonObject request = jsonUtil.parseObj(body);
log.info("原始报文:{}", request.toString());
try {
request.set("empId", "2345");
request.set("department", "Engineering");
lo服务器托管网g.info("修改后报文:{}", request);
return Mono.just(服务器托管网request.toString().getBytes());
} catch (Exception e) {
log.error("修改报文时出错",e);
throw e;
}
}
}
相关代码
https://github.com/eastcukt/demo-gatway
参考
https://amitkhurana92.medium.com/request-body-transformation-in-spring-cloud-gateway-bb9c234d5f3d
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
相关推荐: 【ChatGPT】ChatGPT+MindShow三分钟生成PPT
Yan-英杰的主页 悟已往之不谏 知来者之可追 C++程序员,2024届电子信息研究生 目录 第一步:获取PPT内容大概: 1.打开ChatGPT镜像 2.向他提问,提问格式如下,主题替换成你想获得的信息。比如某本书的拆…