package async; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Properties; import java.util.concurrent.CompletableFuture; public class AsyncSFTPDownload { public static void main(String[] args) { String host = "192.168.10.100"; int port = 22; String user = "dkbs"; String password = "123456"; String[] remoteFiles = {"/home/dkbs/test/large_files/largefile_1.bin", "/home/dkbs/test/large_files/largefile_2.bin","/home/dkbs/test/large_files/largefile_3.bin","/home/dkbs/test/large_files/largefile_4.bin"}; // 远程文件列表 String[] localFiles = {"D:\\test\\largefile_1.bin", "D:\\test\\largefile_2.bin","D:\\test\\largefile_3.bin","D:\\test\\largefile_4.bin"}; // 本地文件路径列表 // 创建一个 CompletableFuture 数组来追踪每个文件的下载任务 CompletableFuture<Void>[] downloadFutures = new CompletableFuture[remoteFiles.length]; for (int i = 0; i < remoteFiles.length; i++) { String remoteFile = remoteFiles[i]; String localFile = localFiles[i]; // 每个文件的异步下载任务 downloadFutures[i] = CompletableFuture.runAsync(() -> downloadFile(host, port, user, password, remoteFile, localFile)) .thenRun(() -> System.out.println("文件下载成功: " + remoteFile)) .exceptionally(ex -> { System.out.println("文件下载失败: " + remoteFile); ex.printStackTrace(); return null; }); } // 当所有下载任务完成后,通知前端 CompletableFuture.allOf(downloadFutures) .thenRun(() -> { // 这里你可以添加通知前端的逻辑,例如返回一个结果或调用API告诉前端所有任务完成 System.out.println("所有文件下载任务已完成,通知前端..."); // 调用前端通知逻辑,如: // notifyFrontend("下载完成"); }) .exceptionally(ex -> { // 处理下载失败的情况,并通知前端 System.out.println("部分文件下载失败,通知前端..."); // 调用前端通知逻辑,如: // notifyFrontend("部分下载失败"); ex.printStackTrace(); return null; }) .join(); } // 下载文件的方法 public static void downloadFile(String remoteHost, int port, String username, String password, String remoteFile, String localFile) { JSch jsch = new JSch(); Session session = null; ChannelSftp channelSftp = null; try { // 1. 创建并连接会话 session = jsch.getSession(username, remoteHost, port); session.setPassword(password); // 2. 设置 SSH 连接参数 Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); // 3. 打开 SFTP 通道 channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); // 4. 下载文件 try (OutputStream os = new FileOutputStream(localFile)) { channelSftp.get(remoteFile, os); } } catch (Exception e) { throw new RuntimeException("下载文件失败: " + remoteFile, e); // 抛出异常 } finally { // 5. 关闭连接 if (channelSftp != null) { channelSftp.disconnect(); } if (session != null) { session.disconnect(); } } } }
线程池下载2,可以直接运行
最新推荐文章于 2024-09-30 12:22:29 发布