Java异步调用实现并发上传下载SMB共享文件
发布日期:2022-02-17 04:52:23
浏览次数:18
分类:技术文章
本文共 12007 字,大约阅读时间需要 40 分钟。
Java异步调用实现并发上传下载SMB共享文件
选择异步
通常情况下,上传(下载)多个SMB共享文件这类任务之间不存在依赖关系,可以考虑通过异步调用的方式来实现上传(下载)的并发执行,来充分利用系统资源以提高计算机的处理能力。
来看一下以下载为例该程序最后的运行日志:
其中最直接的体现,同一组大概3个G的文件,异步执行下载SMB共享文件比非异步所用时间更少,提高了下载效率。下面展示完整的程序代码。
所需依赖
jcifs jcifs 1.2.6 org.slf4j slf4j-api 1.7.25
服务类
共享文件操作类:
- 使用
@Async
注解标注uploadSmbFileAsync
方法和downloadSmbFileAsync
方法为需要异步执行的方法。 - 建议将
jcifs.smb.client.dfs.disabled
属性设置为true
,默认值为false
,在非域环境中,此属性可能很重要,其中基于域的DFS引用通常在JCIFS首次尝试解析路径时运行,这将导致超时,从而导致长启动延迟。
package com.example.smb.service;/** * @author: 博客「成猿手册」 * @description: 对共享文件的操作 * @date: 2020/3/24 */@Componentpublic class SmbFileOperator { private final Logger logger = LoggerFactory.getLogger(SmbFileOperator.class); public SmbFileOperator() { System.setProperty("jcifs.smb.client.dfs.disabled", "true"); } @Async public FutureuploadSmbFileAsync(File file, SmbFile smbFile) throws IOException { this.uploadSmbFile(file, smbFile); return new AsyncResult<>(smbFile.getPath()); } @Async public Future downloadSmbFileAsync(File file, SmbFile smbFile) throws IOException { this.downloadSmbFile(file, smbFile); return new AsyncResult<>(smbFile.getPath()); } public void uploadSmbFile(File file, SmbFile smbfile) throws IOException { logger.info("SMB文件上传开始:{} --> {};size:{}", file.getPath(), smbfile.getPath(), file.length()); try { InputStream in = new BufferedInputStream(new FileInputStream(file)); OutputStream out = new BufferedOutputStream(new SmbFileOutputStream(smbfile)); FileCopyUtils.copy(in, out); logger.info("SMB文件上传成功:{} --> {}", file.getPath(), smbfile.getPath()); } catch (IOException e) { logger.error("SMB文件上传失败:{} --> {}", file.getPath(), smbfile.getPath(), e); throw e; } } public void downloadSmbFile(File file, SmbFile smbfile) throws IOException { logger.info("SMB文件下载开始:{} --> {};size:{}", file.getPath(), smbfile.getPath(), file.length()); try { InputStream in = new BufferedInputStream(new SmbFileInputStream(smbfile)); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); FileCopyUtils.copy(in, out); logger.info("SMB文件下载成功:{} --> {}", smbfile.getPath(),file.getPath()); } catch (IOException e) { logger.error("SMB文件下载失败:{} --> {}", smbfile.getPath(),file.getPath(),e); throw e; } }}
定义异步操作接口:
timeout
:为等待的最长时间数;timeUnit
超时参数的时间单位(秒,分,小时等)。
package com.example.smb.service;/** * @author: 博客「成猿手册」 * @description: 异步操作接口 * @date: 2020/3/26 */public interface SmbExecuteAsync { void downloadSmb(SmbInfo smbFileInfo, long timeout, TimeUnit timeUnit) throws BaseException,IOException; void uploadSmb(SmbInfo smbFileInfo, long timeout, TimeUnit timeUnit) throws BaseException,IOException;}
实现异步操作接口:
- 使用
ThreadLocal
规避多线程访问出现线程不安全的方法:每个线程通过ThreadLocal
的set()
和get
方法确保对变量smbFileTaskThreadLocal
进行访问的时候访问的都是该线程自己的变量。 generateDownloadSmbFileTask
通过递归方式获取文件夹下需要下载的文件完整路径(上传类似)。
package com.example.smb.service.impl;/** * @author: 博客「成猿手册」 * @description: 异步操作接口实现 * @date: 2020/3/26 */@Service("SmbExecuteAsync")public class SmbExecuteAsyncImpl implements SmbExecuteAsync { @Autowired private SmbInstance smbInstance; @Autowired private SmbFileOperator smbFileOperator; private final Logger logger = LoggerFactory.getLogger(SmbExecuteAsyncImpl.class); private final ThreadLocal
> smbFileTaskThreadLocal = new ThreadLocal<>(); @Override public void downloadSmb(SmbInfo smbInfo, long timeout, TimeUnit timeUnit) throws BaseException, IOException { File file = new File(smbInfo.getLocalDirPath()); if (!file.exists()) { throw new BaseException("本地文件不存在:" + smbInfo.getLocalDirPath()); } SmbFile smbFile = smbInstance.getSmbFileInstance( smbInfo.getIp(), smbInfo.getUserName(), smbInfo.getPassWord(), smbInfo.getSmbFilePath()); if (!smbFile.exists()) { throw new BaseException("SMB共享文件不存在:" + smbFile.getPath()); } smbFileTaskThreadLocal.set(new ArrayList<>()); List > futures = new ArrayList<>(); try { generateDownloadSmbFileTask(smbFile, smbInfo, smbInfo.getLocalDirPath(), 1); List tasks = smbFileTaskThreadLocal.get(); Date begindate = new Date(); for (SmbFileTask smbFileTask : tasks) { //将线程储存类ThreadLocal内的多个任务全都通过异步下载方法执行 Future future = smbFileOperator.downloadSmbFileAsync(smbFileTask.getFile(), smbFileTask.getSmbFile()); futures.add(future); } for (Future future : futures) { future.get(timeout, timeUnit); } Date enddate = new Date(); logger.info("下载任务总耗时间" + (enddate.getTime() - begindate.getTime()) / 1000 + "秒"); } catch (InterruptedException | ExecutionException e) { logger.error("SMB共享文件下载存在异常:{}", e); cancleFuture(futures); throw new BaseException("SMB共享文件下载存在异常,强制中断:", e); } catch (TimeoutException e) { logger.error("SMB共享文件下载任务超时:{}", e); cancleFuture(futures); throw new BaseException("SMB共享文件下载存在异常,强制中断:", e); } finally { smbFileTaskThreadLocal.remove(); } } @Override public void uploadSmb(SmbInfo smbInfo, long timeout, TimeUnit timeUnit) throws BaseException, IOException{ File file = new File(smbInfo.getLocalDirPath()); if (!file.exists()) { throw new BaseException("本地文件不存在:" + smbInfo.getLocalDirPath()); } SmbFile smbFile = smbInstance.getSmbFileInstance( smbInfo.getIp(), smbInfo.getUserName(), smbInfo.getPassWord(), smbInfo.getSmbFilePath()); if (!smbFile.exists()) { smbFile.mkdir(); } smbFileTaskThreadLocal.set(new ArrayList<>()); List > futures = new ArrayList<>(); try { NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(smbInfo.getIp(),smbInfo.getUserName(),smbInfo.getPassWord()); generateUploadSmbFileTask(file, smbInfo, smbFile.getURL().toString() + file.getName(),auth); List tasks = smbFileTaskThreadLocal.get(); Date begindate = new Date(); for (SmbFileTask smbFileTask : tasks) { //将线程储存类ThreadLocal内的多个任务全都通过异步下载方法执行 Future future = smbFileOperator.uploadSmbFileAsync(smbFileTask.getFile(), smbFileTask.getSmbFile()); futures.add(future); } for (Future future : futures) { future.get(timeout, timeUnit); } Date enddate = new Date(); logger.info("上传任务总耗时间" + (enddate.getTime() - begindate.getTime()) / 1000 + "秒"); } catch (InterruptedException | ExecutionException e) { logger.error("SMB共享文件上传存在异常:{}", e); cancleFuture(futures); throw new BaseException("SMB共享文件上传存在异常,强制中断:", e); } catch (TimeoutException e) { logger.error("SMB共享文件上传任务超时:{}", e); cancleFuture(futures); throw new BaseException("SMB共享文件上传存在异常,强制中断:", e); } finally { smbFileTaskThreadLocal.remove(); } } private void generateUploadSmbFileTask(File file, SmbInfo smbInfo, String smbFatherDir, NtlmPasswordAuthentication auth)throws BaseException, IOException{ if (file.isFile()) { SmbFile smbFile = new SmbFile(smbFatherDir,auth); smbFileTaskThreadLocal.get().add(new SmbFileTask(file, smbFile)); } else if (file.isDirectory()) { SmbFile smbFile = new SmbFile(smbFatherDir,auth); if (!smbFile.exists() || !smbFile.isDirectory()) { smbFile.mkdir(); } File[] files = file.listFiles(); if (files != null && files.length > 0) { for (File f : files) { //递归调用本方法 以获取完整任务 generateUploadSmbFileTask(f, smbInfo,smbFatherDir+"/"+f.getName(),auth); } } } } private void generateDownloadSmbFileTask(SmbFile smbFile, SmbInfo smbInfo, String fatherDir, int depath) throws IOException,BaseException{ if (depath > 10) { logger.warn("共享目录遍历已超过10层目录" + fatherDir); } if (smbFile.isFile()) { //如果是文件则新建任务并添加至线程ThreadLocal中 String localFilePath = String.format("%s/%s", fatherDir, smbFile.getName()); File localFile = new File(localFilePath); smbFileTaskThreadLocal.get().add(new SmbFileTask(localFile, smbFile)); } else if (smbFile.isDirectory()) { //如果是文件夹,则在本地新建 String localDirPath = fatherDir + "/" + smbFile.getName(); logger.info("SMB共享文件目录开始下载:{} --> {}", smbFile.getPath(), localDirPath); boolean result = new File(localDirPath).mkdir(); logger.info("文件夹创建成功:{},创建标识为:{}", localDirPath, result); //获取该目录下所有文件和目录的绝对路径 SmbFile[] smbFiles = smbFile.listFiles(); if (smbFiles != null && smbFiles.length > 0) { for (SmbFile s : smbFiles) { //递归调用本方法 以获取完整任务 generateDownloadSmbFileTask(s, smbInfo, localDirPath, depath + 1); } } } } private void cancleFuture(List > futures) { for (Future future : futures) { boolean result = future.cancel(true); logger.info("SMB共享文件操作取消,取消结果为{}", result); } }}
实体类
共享文件信息类:
package com.example.smb.entity;import org.springframework.stereotype.Component;/** * @author: 博客「成猿手册」 * @description: 记录共享文件相关信息 * @date: 2020/3/22 */@Componentpublic class SmbInfo { private String ip; private String userName; private String passWord; private String smbFilePath; private String localDirPath; public SmbInfo() { } public SmbInfo(String ip, String userName, String passWord, String smbFilePath, String localDirPath) { this.ip = ip; this.userName = userName; this.passWord = passWord; this.smbFilePath = smbFilePath; this.localDirPath = localDirPath; } //todo:此处省略get和set方法}
SMB文件操作任务类:
package com.example.smb.entity;/** * @author: 博客「成猿手册」 * @description: Smb任务类 * @date: 2020/3/26 */@Componentpublic class SmbFileTask { private File file; private SmbFile smbFile; public SmbFileTask() { } public SmbFileTask(File file, SmbFile smbFile) throws BaseException{ this.file = file; this.smbFile = smbFile; try{ if (this.smbFile.isDirectory()){ throw new BaseException("SmbFileTask不能为目录类型"+smbFile.getPath()); } } catch (SmbException | BaseException e) { throw new BaseException("SmbFileTask不能为目录类型"+smbFile.getPath(),e); } } //todo:此处省略get和set方法}
构建SmbFile文件实例:
package com.example.smb.entity;/** * @author: 博客「成猿手册」 * @description: 构建SmbFile文件实例 * @date: 2020/3/26 */@Componentpublic class SmbInstance { public SmbFile getSmbFileInstance(String ip, String username, String password, String smbfilepath) throws MalformedURLException { NtlmPasswordAuthentication authentication = null; //两种访问方式:有账号密码,无账号密码; if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) { authentication = new NtlmPasswordAuthentication(ip, username, password); } String smburl = String.format("smb://%s/%s", ip, smbfilepath); return new SmbFile(smburl, authentication); }}
调用方法
自己测试用的文件的目录结构大概如图所示:
这里采用了swagger调用controller接口的方式进行了相关测试,代码示例如下:(也可以直接用单元测试)
package com.example.smb.controller;/** * @author: 博客「成猿手册」 * @description: 控制层接口 * @date: 2020/4/8 */@RestController@RequestMapping("/smbExecute")@Api(tags = { "SMB操作相关"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)public class SmbController { @Autowired private SmbExecuteAsync smbExecute; @PostMapping(value = "/smbDownload") @ApiOperation(value = "SMB下载测试") public void smbDownload() throws IOException, BaseException { SmbInfo smbInfo = new SmbInfo("192.168.1.106", "username", "password", "Test/成猿手册的smb目标文件夹/", "D:\\LocalTest\\"); smbExecute.downloadSmb(smbInfo, 1, TimeUnit.HOURS); } @PostMapping(value = "/smbUpload") @ApiOperation(value = "SMB上传测试") public void uploadSmbTest() throws IOException, BaseException { SmbInfo smbInfo = new SmbInfo("192.168.1.106", "username", "password", "Test/", "D:\\LocalTest\\成猿手册的smb目标文件夹\\"); smbExecute.uploadSmb(smbInfo, 1, TimeUnit.HOURS); }}
转载地址:https://blog.csdn.net/qq_41429510/article/details/105750979 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2024年04月16日 16时00分45秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
第十三章 如何设计一个Web框架
2019-04-27
13.1 项目规划
2019-04-27
13.2 自定义路由器设计
2019-04-27
13.3 controller设计
2019-04-27
13.4 日志和配置设计
2019-04-27
13.5 实现博客的增删改
2019-04-27
第十四章 扩展Web框架
2019-04-27
Go语言教程拓展基础篇 (查漏补缺, 献给初学者)
2019-04-27
14.1 静态文件支持
2019-04-27
OS X v10.8 to OS X v10.9 API 差异
2019-04-27
cocos2dx多线程以及线程同步 与 cocos2dx内存管理与多线程问题
2019-04-27
cocos2dx python项目创建
2019-04-27
程序员的成长历程,30岁以内的程序员请勿好大喜功!
2019-04-27
巨头夹缝求生存:菜鸟创业团队的辛酸苦辣 (本文转载)
2019-04-27
前富士康CEO程天纵:创新来自长尾,创业源于创客!
2019-04-27
SVN服务器搭建和使用
2019-04-27
cocos2dx 在windows上实现键盘输入
2019-04-27
iOS 也玩黑苹果,开发者已经将 iOS 底层内核成功运行在诺基亚机子上
2019-04-27
给2014年的中小手游开发商们,撑不下去就嫁了吧!
2019-04-27
NodeJS无所不能:细数10个令人惊讶的NodeJS开源项目
2019-04-27