【问题标题】:Ktor with Spring boot WebFlux web apiKtor 与 Spring Boot WebFlux web api
【发布时间】:2020-05-04 19:48:12
【问题描述】:

我有一个简单的Spring Boot WebFlux api,我正在尝试使用Ktor 来调用它。

这是我的控制器

@RestController
@RequestMapping("api/v1")
class TestController {

    @RequestMapping(method = [RequestMethod.GET], value = ["/values"], produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
    fun sayHello(@RequestParam(value = "name") name:String): Flux<Example> {
        return Flux.interval(Duration.ofSeconds(1))
            .map { Example(number = generateNumber()) }
            .share()
    }

    fun generateNumber(): Int{
        return ThreadLocalRandom.current().nextInt(100)
    }
}

它只是每秒返回一个带有数字的对象

现在在客户端是我想使用 Ktor 获取数据的地方,但我不确定该怎么做。阅读文档,看起来 Scoped streaming 是我需要的,但我不确定如何让它与我的控制器一起使用

这是我目前的客户端代码。

suspend fun getData(): Flow<Example> {
        return flow {
            val client = HttpClient()
            client.get<HttpStatement>("http://192.168.7.24:8080/api/v1/values?name=hello").execute{
        val example = it.receive<Example>()
        emit(example)
    }
        }
    }

当我尝试在 Android 客户端上拨打电话时出现此错误

NoTransformationFoundException:未找到转换:类 io.ktor.utils.io.ByteBufferChannel(Kotlin 反射不是 可用)

所以看起来我不能只将流序列化到我的对象中,那么如何将ByteReadChannel 序列化为对象?

这是我第一次尝试spring和ktor

【问题讨论】:

    标签: android spring-boot kotlin ktor


    【解决方案1】:

    为了能够将数据序列化为对象,您需要手动将数据读入字节数组

     client.get<HttpStatement>("http://192.168.7.24:8080/api/v1/values?name=hello").execute{
            val channel = it.receive<ByteReadChannel>()
            val byteArray = ByteArray(it.content.availableForRead)
            channel.readAvailable(byteArray,0,byteArray.size)
            val example:Example = Json.parse<Example>(stringFromUtf8Bytes(byteArray))
        }
    

    【讨论】:

      【解决方案2】:

      您可以安装一个用于 JSON 序列化/反序列化的插件,这将允许您使用数据类作为通用参数

      https://ktor.io/docs/json.html#jackson

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-05
        • 2019-10-28
        • 2020-07-02
        • 2018-12-24
        • 2016-01-29
        • 2018-08-24
        • 1970-01-01
        相关资源
        最近更新 更多