使用 WebFlux 从资源中读取和解析文件的反应方式?

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

我想知道从资源中读取、解析和提供文件的正确方法是什么。

目前,我在做这样的事情:

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() }

我注意到 JsonObjectDecoder class 在 Netty 中,但我不知道是否可以应用于我的用例。

那么 read/parse 资源文件的反应方式是什么?

你可以看一下Flux.usinghere文件读取。

由于您正在使用 Spring 框架,您还可以查看 DataBufferUtils.

DataBufferUtils 使用 AsynchronousFileChannel 读取文件,并且它还在内部使用 Flux.using 在订阅者读取/取消文件后释放文件。

@Value("classpath:somefile.json")
private Resource resource;


@GetMapping("/resource")
public Flux<DataBuffer> serve(){
   return DataBufferUtils.read(
            this.resource,
            new DefaultDataBufferFactory(),
            4096
    );
}

扩展@vins 的答案后,我得出以下解决方案:

Jackson2JsonDecoder()
    .decodeToMono(
        DataBufferUtils.read(
            DefaultResourceLoader()
                .getResource("$fileName.json"),
            DefaultDataBufferFactory(),
            4096
        ),
        ResolvableType.forClass(JsonModel::class.java), null, null
    )
    .map { it as JsonModel }