在ExchangeFilterFunction

时间:2019-08-03 22:26:13

标签: spring-webflux project-reactor spring-webclient

由于某种原因,doAfterSuccessOrError方法内的context无法从上游获得(填充)。我尝试使用Mono.subscriberContext()访问它(请参阅摘录)。我希望它存在,但由于某种原因却没有。我在做错什么吗?

public class LoggingRequestExchangeFunction implements ExchangeFilterFunction {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
        long start = System.currentTimeMillis();

        return next.exchange(request).doAfterSuccessOrError((res, ex) -> {
            Mono.subscriberContext().map((ctx -> {
                log.info("doAfterSuccessOrError Context {}",ctx);
                // log req/res ...
                return ctx;
            })).subscribe();

        }).subscriberContext( ctx -> {
            log.info("SubscriberContext: {}" , ctx);
            return ctx;
        });
    }
}

这是日志输出

23:16:59.426  INFO [reactor-http-epoll-2] .p.c.LoggingRequestExchangeFunction [] SubscriberContext: Context1{nexmo-tracing-context=TracingContext{{traceId=f04961da-933a-4d1d-85d5-3bea2c47432f, clientIp=N/A}}}
23:16:59.589  INFO [reactor-http-epoll-2] .p.c.LoggingRequestExchangeFunction [] doAfterSuccessOrError Context Context0{}

1 个答案:

答案 0 :(得分:2)

原因是您在var fs = require('fs'); var filetree = DirToObjectArray('path/to/folder/'); function DirToObjectArray(path) { var arr = []; var content = fs.readdirSync(path, { withFileTypes: true }); for (var i=0; i< content.length; i++) { var obj = new Object({ name: "", children: [] }); obj.name = content[i].name; if (content[i].isDirectory()) { obj.children = DirToObjectArray(path + content[i].name + "/"); } arr.push(obj); } return arr; } 内创建了一个新的Mono,它独立于原始反应堆链,因为您是单独订阅的。

如果您只想在内部记录某些内容,则可以选择使用doOnEach运算符,该运算符在信号类型旁边也可以访问上下文。

doAfterSuccessOrError