Skip to content
Client Plugin

重試失敗的請求

程式碼範例: client-retry

預設情況下,Ktor 用戶端不會重試因網路或伺服器錯誤而失敗的請求。 您可以使用 HttpRequestRetry 外掛程式以各種方式為失敗的請求設定重試策略:指定重試次數、設定重試請求的條件,或在重試前修改請求。

新增相依性 ​

HttpRequestRetry 僅需要 ktor-client-core 構件,不需要任何特定的相依性。

安裝 HttpRequestRetry ​

若要安裝 HttpRequestRetry,請將其傳遞給用戶端配置區塊內的 install 函式:

kotlin
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
//...
val client = HttpClient(CIO) {
    install(HttpRequestRetry)
}

如果已安裝 HttpTimeout 外掛程式,應先安裝 HttpRequestRetry,以便能夠為逾時設定重試:

kotlin
val client = HttpClient(CIO) {
    install(HttpRequestRetry) // 應安裝在 HttpTimeout 之前
    install(HttpTimeout) {
       // ...
     }
}

配置 HttpRequestRetry ​

基本重試配置 ​

下方的可執行範例示範了如何設定基本重試策略:

kotlin
val client = HttpClient(CIO) {
    install(HttpRequestRetry) {
        retryOnServerErrors(maxRetries = 5)
        exponentialDelay()
    }
}
  • retryOnServerErrors 函式可在收到來自伺服器的 5xx 回應時啟用請求重試,並指定重試次數。
  • exponentialDelay 指定重試之間的指數延遲,此延遲是使用指數退避演算法(Exponential backoff algorithm)計算的。

您可以從 HttpRequestRetryConfig 深入了解支援的設定選項。

設定重試條件 ​

還有一些配置設定可讓您設定重試請求的條件或指定延遲邏輯:

kotlin
install(HttpRequestRetry) {
    maxRetries = 5
    retryIf { request, response ->
        !response.status.isSuccess()
    }
    retryOnExceptionIf { request, cause -> 
        cause is NetworkError 
    }
    delayMillis { retry -> 
        retry * 3000L 
    } // 分別在 3、6、9 等秒數後重試
}

在重試前修改請求 ​

如果您需要在重試前修改請求,請使用 modifyRequest:

kotlin
install(HttpRequestRetry) {
    // 重試條件
    modifyRequest { request ->
        request.headers.append("x-retry-count", retryCount.toString())
    }
}