使用 WebClient Spring WebFlux 的多个请求
Multiple requests using WebClient Spring WebFlux
我正在尝试使用 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) }
}
看起来,collectList() 过滤掉了在响应主体为空的情况下返回的空单声道。解决方案基本上是,要么使用 Mono.defaultIfEmpty() 方法,要么将 retrieve() 更改为 exchange() ,它总是 returns 一些东西。至少这对我有帮助。
我正在尝试使用 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) }
}
看起来,collectList() 过滤掉了在响应主体为空的情况下返回的空单声道。解决方案基本上是,要么使用 Mono.defaultIfEmpty() 方法,要么将 retrieve() 更改为 exchange() ,它总是 returns 一些东西。至少这对我有帮助。