'flatMap on Mono<byte[]> takes a long time to execute
We have a function in our Spring webflux application which takes in a Mono<byte[]> as below.
public Mono<VirusScanResult> scanFile(Mono<byte[]> bytes) {
int RETRY_COUNT = 1;
return bytes
.flatMap(this::scanFileBytes)
.doOnError(throwable -> log.error("Scanning failed with error", throwable))
.retryWhen(Retry.fixedDelay(RETRY_COUNT, ONE_SECOND));
}
This function is in the service layer of a REST endpoint which accepts Mono<byte[]> as below
public Mono<VirusScanResult> scanFile(
@RequestBody @Schema(type = "string", format = "byte") Mono<byte[]> data) {
log.info("Virus scan requested");
return virusScanService.scanFile(data);
}
The problem is that as the byte[] grows bigger with bigger documents being sent in the bytes.flatMap in the first code snippet above takes a lot of time since it iterates over the huge byte<>. Is there a way to extract the byte[] from the Mono<byte[]> without using flatMap and which is more effecient. At the moment when a 25MB file is sent to the Rest API, bytes.flatMap code takes around 13 seconds to execute
I also tried with code snippet below with Mono but again it takes time at filePartMono.flatMap
public Mono<VirusScanResult> scanWithFilePart(@RequestPart Mono<Part> filePartMono) {
log.info("scanWithFilePart Controller started");
return filePartMono
.flatMap(
fp ->
DataBufferUtils.join(fp.content())
.map(dataBuffer -> dataBuffer.asByteBuffer().array()))
.flatMap(bytes -> virusScanService.scanFileBytes(bytes));
}
Kindly advise
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
