【问题标题】:Multiple requests using WebClient Spring WebFlux使用 WebClient Spring WebFlux 的多个请求
【发布时间】:2020-01-30 11:34:00
【问题描述】:

我正在尝试并行使用 WebClient 发出请求,但我不知道该怎么做, 因为无论我做什么,代码都不会等待请求完成。如果我只执行一个请求(注释片段),一切正常。有人可以帮我吗?

@RequestMapping(method = [RequestMethod.POST], path = ["/upload/{batchId}"])
fun uploadFile(@RequestPart("file") file: Mono<FilePart>,
                       @PathVariable("batchId") batchId:String,
                       @RequestHeader("FILE-SIZE") fileSize:Int): Mono<ServiceResponse> {
    val webClient = WebClient.create(commandEndpoint)
    // return webClient.put().uri(seriesPath).retrieve().bodyToMono(String::class.java).map { ServiceResponse(it,0) }
    return file.map{it.transferTo(Paths.get(storagePath,"excel"))}
        .map{excelWorkbookToMetadata(WorkbookFactory.create(Paths.get(storagePath,"excel").toFile()))}
        .flatMapMany{Flux.fromIterable(it)}
        .flatMap {
            it.transactionId = batchId
            when (it) {
                is SeriesMetadata -> webClient.put().uri(seriesPath,it.id)
                    .body(BodyInserters.fromObject(it))
                    .retrieve()
                    .onStatus({ it == HttpStatus.BAD_REQUEST },{
                        println("ERROR")
                        Mono.error(RuntimeException("blah")) }).toMono()
                else -> Mono.error(NotImplementedError(""))
            }

        }
        .collectList()
        .map {ServiceResponse(batchId, it.size*2) }
}

【问题讨论】:

标签: spring kotlin spring-webflux project-reactor reactor-netty


【解决方案1】:

看来,collectList() 过滤掉了在响应正文为空的情况下返回的空单声道。解决方案基本上是,要么使用 Mono.defaultIfEmpty() 方法,要么将 retrieve() 更改为 exchange() ,它总是返回一些东西。至少这对我有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 2020-05-04
    • 2020-07-12
    • 2020-09-02
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    相关资源
    最近更新 更多