背景 使用Spring Cloud Gateway作為網關時經常會需要對報文內的json數據進行修改,但是目前看到的實現方法看起來都很複雜,這裡提供一種使用Spring官方提供的ModifyRequestBodyGatewayFilterFactory類來修改json報文的方法 依賴 Spring ...
背景
使用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
@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
@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