Reactive way to read and parse file from resources using WebFlux?

試著忘記壹切 提交于 2021-02-08 06:59:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!