使用WebFlux从资源读取和解析文件的反应方式? [英] Reactive way to read and parse file from resources using WebFlux?

查看:544
本文介绍了使用WebFlux从资源读取和解析文件的反应方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

在扩展@vins答案之后,我来到了以下解决方案:

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 }

这篇关于使用WebFlux从资源读取和解析文件的反应方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆