修改经过Spring Gateway的Json数据

背景

使用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<T, R>接口完成对json数据的处理

自定义filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Component
@Slf4j
public class RequestModifyFilter implements GlobalFilter, Ordered {
@Autowired
private ModifyRequestBodyGatewayFilterFactory modifyRequestBodyFilter;
@Autowired
private JsonRequestBodyRewriteService jsonRequestBodyRewriteService;

@Override
public Mono<Void> 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Service
@Slf4j
public class JsonRequestBodyRewriteService implements RewriteFunction<byte[], byte[]> {
@Override
public Publisher<byte[]> apply(ServerWebExchange exchange, byte[] body) {
jsonObject request = jsonUtil.parseObj(body);
log.info("原始报文:{}", request.toString());
try {
request.set("empId", "2345");
request.set("department", "Engineering");

log.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