【问题标题】:Spring WebClient - logging is2xxSuccessful HTTPStatusSpring WebClient - 记录 is2xxSuccessful HTTPStatus
【发布时间】:2021-12-02 09:15:34
【问题描述】:

我正在使用 Spring WebClient 下载文件,如下所示:

private void dnloadFileAPI(String theId, String destination) {
        log.info("Downloading file.. " + theId);
        Flux<DataBuffer> dataBuffer = webClient
                .get()
                .uri("/some/fancy/" + theId + "/api")
                .retrieve()
                .onStatus(HttpStatus::is2xxSuccessful, response -> Mono.just(new CustomException("Success")))
                .bodyToFlux(DataBuffer.class);
        DataBufferUtils.write(dataBuffer, Paths.get(destination), StandardOpenOption.CREATE).share().block();
    }

文件可以正常下载。我唯一苦苦挣扎的是,当响应为 200 时,我只想像这样记录一行:

log.info("{}", theId + " - File downloaded successfully")

我也试过了,但没有得到我想要的东西 - How to log Spring WebClient response

简而言之,有没有什么方法可以在不单独写CustomException的情况下实现?在这里感到迷茫和不知所措。任何这方面的指针都将受到高度赞赏。

【问题讨论】:

    标签: java spring spring-boot spring-webflux project-reactor


    【解决方案1】:

    我认为在bodyToFlux(DataBuffer.class) 行之后添加以下内容将是您所需要的

    .doOnComplete(() -> log.info("File downloaded successfully"))
    

    类似的东西

    private void dnloadFileAPI(String theId, String destination) {
        log.info("Downloading file.. " + theId);
        Flux<DataBuffer> dataBuffer = webClient
            .get()
            .uri("/some/fancy/" + theId + "/api")
            .retrieve()
            .bodyToFlux(DataBuffer.class)
            .doOnComplete(() -> log.info("File downloaded successfully"));
        DataBufferUtils.write(dataBuffer, Paths.get(destination), StandardOpenOption.CREATE).share().block();
    }
    

    【讨论】:

    • 当...!!这么多要学!!! .doOnComplete(..) 正是我想要的。 !我现在不需要.onStatus(...)。感谢一百万@athom。
    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 2018-02-19
    • 2020-04-05
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2021-02-10
    相关资源
    最近更新 更多