本文介紹了Spring Reactive應用程序上的請求/響應正文的副本?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在研究訪問HTTP請求和響應正文的最佳方法,以便在Spring反應性應用程序中進行跟蹤。
對于以前的版本,我們利用Servlet篩選器和Servlet請求包裝器來使用傳入請求的輸入流,并保留它的副本以用于跟蹤的異步處理(我們將它們發送到Elasticearch)。
但是對于一個Spring Reactive應用程序(使用WebFlux),我想知道在請求被解碼之前訪問它們的最合適的方式是什么。有什么想法嗎?
推薦答案
事實證明,這可以使用提供的修飾符分別實現:ServerWebExchangeDecorator
、ServerHttpRequestDecorator
和ServerHttpResponseDecorator
。
下面是一個示例請求修飾符,它在請求的默認訂閱者讀取內容時累積DataBuffer
內容:
@Slf4j
public class CachingServerHttpRequestDecorator extends ServerHttpRequestDecorator {
@Getter
private final OffsetDateTime timestamp = OffsetDateTime.now();
private final StringBuilder cachedBody = new StringBuilder();
CachingServerHttpRequestDecorator(ServerHttpRequest delegate) {
super(delegate);
}
@Override
public Flux<DataBuffer> getBody() {
return super.getBody().doOnNext(this::cache);
}
@SneakyThrows
private void cache(DataBuffer buffer) {
cachedBody.append(UTF_8.decode(buffer.asByteBuffer())
.toString());
}
public String getCachedBody() {
return cachedBody.toString();
}
只需確保在修飾WebFilter
傳遞的ServerWebExchange
時,也重寫getRequest()
以返回請求修飾符:
public final class PartnerServerWebExchangeDecorator extends ServerWebExchangeDecorator {
private final ServerHttpRequestDecorator requestDecorator;
private final ServerHttpResponseDecorator responseDecorator;
public PartnerServerWebExchangeDecorator(ServerWebExchange delegate) {
super(delegate);
this.requestDecorator = new PartnerServerHttpRequestDecorator(delegate.getRequest());
this.responseDecorator = new PartnerServerHttpResponseDecorator(delegate.getResponse());
}
@Override
public ServerHttpRequest getRequest() {
return requestDecorator;
}
@Override
public ServerHttpResponse getResponse() {
return responseDecorator;
}
}
在過濾器上:
@Component
public class TracingFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return chain.filter(new PartnerServerWebExchangeDecorator(exchange));
}
}
可以這樣使用的函數(注意靜態導入的函數):
@Bean
public HttpHandler myRoute(MyHandler handler) {
final RouterFunction<ServerResponse> routerFunction =
route(POST("/myResource"), handler::persistNotification);
return webHandler(toWebHandler(routerFunction))
.filter(new TracingFilter())
.build();
}
這篇關于Spring Reactive應用程序上的請求/響應正文的副本?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,