问题
I wonder what is the correct way to read, parse and serve a file from resources.
Currently, I do something like this:
fun getFile(request: ServerRequest): Mono<ServerResponse> {
val parsedJson =
objectMapper.readValue(readFile("fileName.json"), JsonModel::class.java)
// modify parsed json
return ok().contentType(APPLICATION_JSON).bodyValue(parsedJson)
}
private fun readFile(fileName: String) =
DefaultResourceLoader()
.getResource(fileName)
.inputStream.bufferedReader().use { it.readText() }
I've noticed JsonObjectDecoder class in Netty, but I don't know if can be applied to my use case.
What is the reactive way to do read/parse resource file then?
回答1:
After expanding @vins answer, I've came to following solution:
Jackson2JsonDecoder()
.decodeToMono(
DataBufferUtils.read(
DefaultResourceLoader()
.getResource("$fileName.json"),
DefaultDataBufferFactory(),
4096
),
ResolvableType.forClass(JsonModel::class.java), null, null
)
.map { it as JsonModel }
回答2:
You can take a look at Flux.using
here for file read.
As you are using Spring framework, You can also take a look at the DataBufferUtils
.
This DataBufferUtils
uses AsynchronousFileChannel
to read the file and it also internally uses Flux.using
to release the file once the file is read / cancelled by the subscriber.
@Value("classpath:somefile.json")
private Resource resource;
@GetMapping("/resource")
public Flux<DataBuffer> serve(){
return DataBufferUtils.read(
this.resource,
new DefaultDataBufferFactory(),
4096
);
}
来源:https://stackoverflow.com/questions/61139186/reactive-way-to-read-and-parse-file-from-resources-using-webflux