Arn*_*lle 5 project-reactor spring-webflux
Spring Boot 2.1.5 项目反应堆 3.2.9
在我的 webflux 项目中,我广泛使用反应器上下文来传递一些值。
我设置了一个过滤器,并试图记录上下文中的内容,并在出现错误/成功时记录不同的内容。
我检查了这个文档:https : //projectreactor.io/docs/core/release/reference/#context
我仍然在努力(尤其是在错误方面)来获得它。
基本上,我有这个过滤器:
@Component
public class MdcWebFilter implements WebFilter {
@NotNull
@Override
public Mono<Void> filter(@NotNull ServerWebExchange serverWebExchange,
WebFilterChain webFilterChain) {
Mono<Void> filter = webFilterChain.filter(serverWebExchange);
return filter
.doAfterSuccessOrError(new BiConsumer<Void, Throwable>() {
@Override
public void accept(Void aVoid, Throwable throwable) {
//Here i would like to be able to access to the request's context
System.out.println("doAfterSuccessOrError:" + (throwable==null ? "OK" : throwable.getMessage())+"log the context");
}
})
.doOnEach(new Consumer<Signal<Void>>() {
@Override
public void accept(Signal<Void> voidSignal) {
//Here i have the context but i don't really know if i am in success or error
System.out.println("doOnEach:"+"Log OK/KO and the exception" + voidSignal.getContext());
}
})
.subscriberContext(context -> context.put("somevar", "whatever"));
}
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用 flatMap() 和 Mono.subscriberContext() 但我不确定如何正确插入过滤器(尤其是错误时)。
实现这一目标的最佳方法是什么?
小智 6
我不确定是否可以从 WebFilter 内访问请求反应器上下文。WebFilter 上下文存在于另一个 Mono 链中。但确实可以将属性与请求关联起来,并能够在请求生命周期内获取这些属性Reactive Web 的 RequestContextHolder 与 Servlet API 非常相似。
控制器:
@GetMapping(path = "/v1/customers/{customerId}")
public Mono<Customer> getCustomerById(
@PathVariable("customerId") String customerId,
ServerWebExchange serverWebExchange)
{
serverWebExchange.getAttributes().put("traceId", "your_trace_id");
return customerService.findById(customerId);
}
Run Code Online (Sandbox Code Playgroud)
网页过滤器:
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// ...
String traceId = exchange.getAttributeOrDefault("traceId", "default_value_goes_here");
//...
return chain.filter(exchange);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6422 次 |
| 最近记录: |