Spring Boot线程池实现SFTP文件下载失败重跑方案咨询
SFTP批量下载失败重试解决方案
问题解答
1. 重跑失败文件的实现思路
- 记录失败任务:捕获下载异常时,记录目标文件名及当前重试次数
- 重试策略控制:设置最大重试次数和重试间隔,避免短时间内重复请求加重服务器负担
- 线程安全处理:用线程安全容器存储待重试任务,防止多线程环境下的并发问题
2. 常用内置/现成实现方式
Spring生态下推荐使用Spring Retry组件,通过注解即可快速实现方法级别的重试逻辑,无需手动编写循环重试代码;也可以选择Guava Retryer,但Spring Retry更适配Spring Boot项目环境。
基于现有代码的重试改造
以下提供两种改造方案,适配不同需求场景:
方案一:手动实现重试逻辑(无需额外依赖)
直接在现有方法中添加重试控制逻辑,适合不想引入新依赖的场景:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.SftpException; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; public class GechubServiceImpl implements GechubService { private static final Logger log = LoggerFactory.getLogger(GechubServiceImpl.class); // 线程安全容器,存储待重试文件及已重试次数 private final ConcurrentHashMap<String, Integer> retryTaskMap = new ConcurrentHashMap<>(); // 最大重试次数 private static final int MAX_RETRY_TIMES = 3; // 重试间隔(毫秒) private static final long RETRY_INTERVAL = 2000; @Autowired private GechubConfig gechubConfig; @Autowired private GechubUtils gechubUtils; @Autowired private ExecutorService executorService; // 移除原构造方法,避免覆盖Spring自动注入的Bean // public void GecHubDownloader(...) {} public String downloadFromGecHub(String fileName) throws JSchException { int currentRetryCount = retryTaskMap.getOrDefault(fileName, 0); String response = "No File found"; ChannelSftp channelSftp = null; try { channelSftp = gechubUtils.getSftpChannel(); if (channelSftp != null) { channelSftp.cd(gechubConfig.getGechubOutDir()); log.info("Remote Working Directory --> {}", channelSftp.pwd()); List<ChannelSftp.LsEntry> fileList = channelSftp.ls("*"); for (ChannelSftp.LsEntry file : fileList) { if (!file.getAttrs().isDir() && !file.getFilename().startsWith(".") && file.getFilename().equals(fileName)) { channelSftp.get(file.getFilename(), "src/main/resources/" + file.getFilename()); response = "File downloaded successfully"; // 下载成功,移除重试记录 retryTaskMap.remove(fileName); return response; } } } return response; } catch (SftpException e) { log.error("Download file {} failed, retry count: {}, error: {}", fileName, currentRetryCount, e.getMessage()); if (currentRetryCount < MAX_RETRY_TIMES) { retryTaskMap.put(fileName, currentRetryCount + 1); // 提交延迟重试任务到线程池 executorService.submit(() -> { try { TimeUnit.MILLISECONDS.sleep(RETRY_INTERVAL); downloadFromGecHub(fileName); } catch (Exception ex) { log.error("Final retry for file {} failed, exceed max retry times", fileName); retryTaskMap.remove(fileName); } }); return "Download failed, will retry " + (currentRetryCount + 1) + " time(s)"; } else { retryTaskMap.remove(fileName); return "Download failed, exceed max retry times (" + MAX_RETRY_TIMES + ")"; } } finally { if (channelSftp != null) { gechubUtils.disconnectChannel(channelSftp); } } } }
关键修改点:
- 新增
ConcurrentHashMap存储待重试任务,保证多线程环境下的安全性 - 设置重试次数上限和间隔,避免无效重复请求
- 异常捕获后判断是否继续重试,通过线程池实现延迟重试
- 下载成功后清理重试记录,防止重复处理
方案二:使用Spring Retry实现(简洁高效)
通过Spring注解快速实现重试逻辑,适合Spring Boot项目:
- 添加依赖(Maven):
<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
- 开启重试功能:在Spring Boot启动类添加
@EnableRetry注解 - 改造下载方法:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Recover; import org.springframework.retry.annotation.Retryable; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.SftpException; import java.util.List; public class GechubServiceImpl implements GechubService { private static final Logger log = LoggerFactory.getLogger(GechubServiceImpl.class); @Autowired private GechubConfig gechubConfig; @Autowired private GechubUtils gechubUtils; @Autowired private ExecutorService executorService; // 指定重试异常类型、最大次数、重试间隔 @Retryable(value = SftpException.class, maxAttempts = 3, backoff = @Backoff(delay = 2000)) public String downloadFromGecHub(String fileName) throws JSchException, SftpException { String response = "No File found"; ChannelSftp channelSftp = gechubUtils.getSftpChannel(); try { if (channelSftp != null) { channelSftp.cd(gechubConfig.getGechubOutDir()); log.info("Remote Working Directory --> {}", channelSftp.pwd()); List<ChannelSftp.LsEntry> fileList = channelSftp.ls("*"); for (ChannelSftp.LsEntry file : fileList) { if (!file.getAttrs().isDir() && !file.getFilename().startsWith(".") && file.getFilename().equals(fileName)) { channelSftp.get(file.getFilename(), "src/main/resources/" + file.getFilename()); response = "File downloaded successfully"; return response; } } } return response; } finally { if (channelSftp != null) { gechubUtils.disconnectChannel(channelSftp); } } } // 所有重试失败后的回调方法 @Recover public String recoverDownload(SftpException e, String fileName) { log.error("Final download failed for file {}, error: {}", fileName, e.getMessage()); return "Download failed, all retries completed"; } }
关键说明:
@Retryable注解:指定触发重试的异常类型、最大重试次数、重试间隔@Recover注解:定义重试全部失败后的兜底逻辑,比如记录日志、返回最终失败信息- 无需手动管理重试状态,Spring Retry自动完成重试流程
注意事项
- 线程池建议通过
@Configuration类统一配置,不要在构造方法中创建,避免Spring Bean注入冲突 - 重试间隔和次数需根据实际网络环境调整,避免触发SFTP服务器的限流机制
- 批量下载场景下,建议先获取全量待下载文件列表,再批量提交到线程池处理,便于跟踪整体进度
内容的提问来源于stack exchange,提问作者venki
相关产品推荐
相关产品推荐

