Kotlin协程-是否有默认超时时间?

5
我正在尝试连接到一个偶尔会变慢的服务器。我使用的ktor客户端会崩溃,并显示以下异常:Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 15000 ms,即使我没有指定任何限制。是否集成了默认超时时间?
最小示例:
main.kt
import io.ktor.client.engine.cio.*
import io.ktor.client.features.*
import io.ktor.client.request.*


suspend fun main() {
    val client = HttpClient(CIO) {
        install(HttpTimeout) {
            requestTimeoutMillis = HttpTimeout.INFINITE_TIMEOUT_MS
            connectTimeoutMillis = HttpTimeout.INFINITE_TIMEOUT_MS
            socketTimeoutMillis = HttpTimeout.INFINITE_TIMEOUT_MS
        }
    }

    val foo = client.get<String>("http://slowwly.robertomurray.co.uk/delay/20000/url/http://www.google.co.uk")
    println(foo)

}

build.gradle.kts

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.4.10"
    application
}
group = "me.oehmj"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

val ktor_version: String by project
val kotlin_serialization_version: String by project
val kotlin_coroutines_version: String by project

dependencies {
    implementation("io.ktor:ktor-client-cio:$ktor_version")
    implementation("io.ktor:ktor-client-auth-jvm:$ktor_version")
    implementation("io.ktor:ktor-client-logging-jvm:$ktor_version")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version")
}

tasks.withType<KotlinCompile>() {
    kotlinOptions.jvmTarget = "1.8"
}
application {
    mainClassName = "MainKt"
}

gradle.properties

kotlin.code.style=official
ktor_version=1.4.2
kotlin_coroutines_version=1.4.1

Ktor-HttpTimeout模块似乎没有起作用。 有没有建议我如何延长超时时间?

1个回答

6

看着文档,你应该这样做:

val client = HttpClient(CIO) {
    engine {
        requestTimeout = 0 // 0 to disable, or a millisecond value to fit your needs
    }
}

默认值为15秒。

你可以在这里阅读更多关于ktor引擎的信息here

enter image description here


啊,我不知道还有一个引擎级别的配置。非常感谢! - Johannes Oehm
当我尝试使用0时,我得到了这个:IllegalArgumentException: 只允许使用正数超时值,要使用无限超时,请使用HttpTimeout.INFINITE_TIMEOUT_MS。 - hemisphire

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接