Ktor 中使用 readUTF8Line 时如何设置读取通道缓冲区大小

问题描述 投票:0回答:1

我在 JVM 中使用 Ktor 2.3.2,并且从服务器接收 HTTP 响应作为流,其中包含行(用 LF 分隔)。

我已经有以下代码:

httpClient.preparePost("/some/api/endpoint".apiUrl) {
    contentType(ContentType.Application.Json)
    setBody("test")
}.execute {
    val channel: ByteReadChannel = it.body()
    var line: String?
    do {
        line = channel.readUTF8Line()
        if (line != null) {
            // Do stuff with this line
        }
    }  while (line != null)
}                 

所讨论的 HTTP 客户端变量是通过以下方式构造的:

    val httpClient = HttpClient(Java) {
        install(ContentNegotiation) {
            json(Json { ignoreUnknownKeys = true })
        }
        install(ContentEncoding) {
            gzip(1.0f)
            deflate(0.6f)
            identity(0.1f)
        }
        install(HttpRequestRetry) {
            retryOnExceptionIf(3) { b, throwable ->
                logger.warn("Warning: Exception ${throwable::class.simpleName} for ${b.url.buildString()}")
                throwable.printStack()
                throwable.hasCause<HttpRequestTimeoutException>()
            }
            retryOnExceptionIf(100) { b, throwable ->
                logger.warn("Warning: Exception ${throwable::class.simpleName} for ${b.url.buildString()}")
                throwable.printStack()
                throwable.hasCause<IOException>()
            }
            constantDelay(200, 1000)
        }
        // Enable request timeouts:
        //install(HttpTimeout)
        install(HttpSend) {
            maxSendCount = 1000
        }
        // Enable request logging:
        //install(Logging)
        expectSuccess = true
        engine {
            threadsCount = 1
        }
    }.apply {
        plugin(HttpSend).intercept { request ->
            onHttpRequest(request)
        }
    }

看起来

channel: ByteReadChannel
被缓冲了,所以线路是批量进来的。我想让这个通道不缓冲或至少减少缓冲区大小,以便我可以更频繁地对传入线路进行操作。

有没有办法使用 Ktor 来做到这一点,还是我必须使用不同的 HTTP 客户端?

kotlin http stream jvm ktor
1个回答
0
投票

您可以尝试使用

ByteReadChannel.consumeEachBufferRange
来运行您在通道的每个缓冲区上传递给它的 lambda

© www.soinside.com 2019 - 2024. All rights reserved.