Gradle任务uploadWildFlyWar失败自动重试配置需求
为Gradle uploadWildFlyWar任务添加自动重试机制
问题场景
uploadWildFlyWar任务会因502 Bad Gateway错误间歇性失败,手动重新运行通常能成功,需要实现失败后自动重试3次,每次间隔5秒,若3次都失败则判定任务真实失败。
原任务代码:
uploadWildFlyWar { dependsOn createAndCopySasJar description 'Uploads the Wild-fly war' group 'publishing' repositories { mavenDeployer { repository(url: repoProps["remoteRepoUrlVal"]) { authentication(userName: repoProps["remoteRepoUsernameVal"], password: repoProps["remoteRepoPasswordVal"]) } } } }
失败报错信息:
执行失败原因:
任务':commons:src:uploadWildFlyWar'执行失败。
无法发布配置'wildFlyWar'
部署构件失败:无法传输构件common:wildfly-startup:war:Branch-8.8.3.5c8e849b5到/从远程仓库(https://artifactory.abc.com/artifactory/cprms-build-branch):传输文件失败:https://artifactory.abc.com/artifactory/cprms-build-branch/com/ideas/cpro/common/wildfly-startup/Branch-8.8.3.5c8e849b5/wildfly-startup-Branch-8.8.3.5c8e849b5.war。
返回码:502,原因短语:Bad Gateway。
解决方案
方案一:自定义重试逻辑(无需额外插件)
直接在任务中添加重试逻辑,仅针对502错误进行重试:
uploadWildFlyWar { dependsOn createAndCopySasJar description 'Uploads the Wild-fly war' group 'publishing' repositories { mavenDeployer { repository(url: repoProps["remoteRepoUrlVal"]) { authentication(userName: repoProps["remoteRepoUsernameVal"], password: repoProps["remoteRepoPasswordVal"]) } } } def maxRetries = 3 def retryDelayMs = 5000 // 5秒间隔 doLast { int attemptCount = 0 boolean uploadSuccess = false while (attemptCount < maxRetries && !uploadSuccess) { attemptCount++ try { // 触发上传动作 publishing.publish() uploadSuccess = true logger.lifecycle("uploadWildFlyWar 第${attemptCount}次尝试成功") } catch (Exception e) { // 仅在出现502错误时重试 if (e.message.contains("502") || e.message.contains("Bad Gateway")) { if (attemptCount < maxRetries) { logger.warn("uploadWildFlyWar 第${attemptCount}次尝试失败,5秒后重试...") Thread.sleep(retryDelayMs) } else { logger.error("uploadWildFlyWar 已重试${maxRetries}次仍失败,任务终止") throw e } } else { // 非502错误直接抛出,不重试 throw e } } } } }
方案二:使用Gradle Retry插件(代码更简洁)
如果允许引入外部插件,推荐使用官方维护的retry插件:
- 先在build.gradle中引入插件:
plugins { id 'org.gradle.retry' version '1.4.0' }
- 为任务配置重试规则:
uploadWildFlyWar { dependsOn createAndCopySasJar description 'Uploads the Wild-fly war' group 'publishing' repositories { mavenDeployer { repository(url: repoProps["remoteRepoUrlVal"]) { authentication(userName: repoProps["remoteRepoUsernameVal"], password: repoProps["remoteRepoPasswordVal"]) } } } retry { maxRetries = 3 delay = 5000 // 指定仅重试502相关异常 retryOn { throwable -> throwable.message?.contains("502") || throwable.message?.contains("Bad Gateway") } } }
说明
- 方案一适合无法引入外部插件的场景,完全自定义逻辑,灵活性高。
- 方案二使用官方插件,代码更简洁易维护,是推荐的实现方式。
- 两种方案都只针对502错误重试,避免对其他类型错误做无意义重试。
内容的提问来源于stack exchange,提问作者Parag Kadam
相关产品推荐
相关产品推荐

