📜  gradle 在从网络下载工件时抛出错误.重试下载 (1)

📅  最后修改于: 2023-12-03 15:01:03.738000             🧑  作者: Mango

Gradle 在从网络下载工件时抛出错误.重试下载

在使用 Gradle 构建项目时,有可能会从网络下载依赖库或插件。但是网络不稳定或者依赖库或插件链接不存在等原因,可能会导致下载失败并抛出错误。此时可以使用 Gradle 的重试下载功能,尝试重新下载工件。

错误信息

当出现下载工件失败时,可能会出现类似以下错误信息:

Could not resolve com.example:dependency:1.0.0.
...
Caused by: org.gradle.internal.resolve.ModuleVersionResolveException: Could not resolve com.example:dependency:1.0.0.
...
Caused by: org.gradle.api.resources.ResourceException: Could not get resource 'https://maven.example.com/com/example/dependency/1.0.0/dependency-1.0.0.pom'.
...
Caused by: javax.net.ssl.SSLException: Read timed out
解决方案

针对下载失败的错误信息,可以尝试使用 Gradle 的重试下载功能,让 Gradle 自动尝试重新下载工件。在构建时加入以下配置:

repositories {
    mavenCentral() // or any other remote repository you want
    retry {
        maxRetries = 3 // number of times to retry downloading
        delayBeforeRetry = 1000 // delay (in milliseconds) before each retry
        includeStatuses = [ 500, 502, 503, 504, 408, 429 ] // optional: HTTP status codes to include in retry

        // The following are also optional and have their respective default values.
        // They can be changed to fine-tune the retry behavior.
        exponentialBackoffBase = 2 // multiplier for increase in delay after each retry
        useExponentialBackoff = true // whether or not to use exponential backoff
        jitterDuration = 1000 // maximum random delay (in milliseconds) to add to each retry delay
    }
}

以上配置会将 Maven 中央仓库设置为重试下载的对象,并配置重试下载的参数:maxRetries 表示最多尝试重新下载的次数,delayBeforeRetry 表示每次重试之间的间隔时间,includeStatuses 表示指定需要重试的 HTTP 状态码。其他参数均为可选参数,可以根据实际情况进行调整。

如果直接在 build.gradle 文件中加入以上配置,会对整个项目的构建过程生效。也可以将以上配置独立成一个文件,例如 retry.gradle,然后在 build.gradle 文件中进行引入:

apply from: 'retry.gradle'

这样配置只会对当前模块生效,而不会对整个项目生效。