You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Groovy中为FTP文件检索设置时间限制及异常处理?

在Groovy中实现带超时限制的FTP文件检索

我来帮你搞定这个需求——给FTP文件检索加上时间限制,超时就抛带错误码的异常,成功就返回提示。下面是完整的实现方案,包含自定义异常和核心逻辑:

核心思路

  • 用ExecutorService异步执行FTP操作,通过get()方法设置超时时间,比单纯用线程更易控制
  • 自定义带错误码的超时异常,方便业务层识别和处理
  • 严格管理FTP连接资源,确保无论成功还是失败都能关闭连接

完整实现代码

import org.apache.commons.net.ftp.FTPClient
import org.apache.commons.net.ftp.FTP
import org.apache.commons.net.ftp.FTPFile
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

// 自定义带错误码的FTP超时异常
class FTPTimeoutException extends Exception {
    int errorCode

    FTPTimeoutException(String message, int errorCode) {
        super(message)
        this.errorCode = errorCode
    }
}

start()

def start() {
    // 定义超时时间(可根据需求调整)
    final int RETRIEVE_TIMEOUT = 30 * 1000 // 30秒
    final int TIMEOUT_ERROR_CODE = 1001 // 自定义超时错误码

    // FTP连接参数(根据实际环境配置)
    def ftpHost = "your-ftp-host"
    def ftpPort = 21
    def ftpUser = "your-username"
    def ftpPass = "your-password"
    def targetFilePath = "/path/to/target/file" // 要检索的文件路径

    ExecutorService executor = Executors.newSingleThreadExecutor()
    FTPClient ftpClient = new FTPClient()

    try {
        // 提交FTP检索任务到线程池
        def future = executor.submit({
            try {
                // 初始化FTP连接
                ftpClient.connect(ftpHost, ftpPort)
                ftpClient.login(ftpUser, ftpPass)
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE)
                ftpClient.enterLocalPassiveMode()

                // 检索文件(这里以获取文件信息为例,也可以替换为下载逻辑)
                FTPFile[] files = ftpClient.listFiles(targetFilePath)
                if (files == null || files.length == 0) {
                    throw new Exception("目标文件不存在")
                }

                // 这里可以添加文件下载逻辑,比如ftpClient.retrieveFile(...)
                return "文件检索成功:${files[0].getName()}"
            } catch (Exception e) {
                throw new Exception("FTP操作失败:${e.message}")
            }
        })

        // 等待任务完成,超时则抛出异常
        def result = future.get(RETRIEVE_TIMEOUT, TimeUnit.MILLISECONDS)
        println(result)
    } catch (TimeoutException e) {
        // 捕获超时,抛出自定义带错误码的异常
        throw new FTPTimeoutException("FTP文件检索超时,已超过${RETRIEVE_TIMEOUT/1000}秒", TIMEOUT_ERROR_CODE)
    } catch (Exception e) {
        // 处理其他FTP操作异常
        println("操作失败:${e.message}")
    } finally {
        // 确保关闭FTP连接和线程池
        if (ftpClient.isConnected()) {
            try {
                ftpClient.logout()
                ftpClient.disconnect()
            } catch (Exception e) {
                println("关闭FTP连接失败:${e.message}")
            }
        }
        executor.shutdown()
    }
}

关键细节说明

  • 自定义异常:FTPTimeoutException携带errorCode,上层调用方可以通过这个错误码快速判断是超时导致的失败
  • 超时控制:通过ExecutorService.submit()提交任务,再用future.get(timeout, unit)设置超时时间,超时会触发TimeoutException
  • 资源管理:finally块中强制关闭FTP连接和线程池,避免资源泄漏
  • FTP操作:包含了标准的FTP连接、登录、被动模式设置,你可以根据实际需求替换listFiles为retrieveFile来实现文件下载的超时控制

内容的提问来源于stack exchange,提问作者chanbasha sk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:09:42