• Java异步调用实现并发上传下载SMB共享文件


    Java异步调用实现并发上传下载SMB共享文件

    选择异步

    通常情况下,上传(下载)多个SMB共享文件这类任务之间不存在依赖关系,可以考虑通过异步调用的方式来实现上传(下载)的并发执行,来充分利用系统资源以提高计算机的处理能力。

    来看一下以下载为例该程序最后的运行日志:

    其中最直接的体现,同一组大概3个G的文件,异步执行下载SMB共享文件比非异步所用时间更少,提高了下载效率。下面展示完整的程序代码。

    所需依赖

    <!-- 建议使用SMB的1.2.6版本比较稳定 -->
    <dependency> 
      <groupId>jcifs</groupId>  
      <artifactId>jcifs</artifactId>  
      <version>1.2.6</version> 
    </dependency>
    <!-- 日志打印需要引入slf4j日志的依赖 -->
    <dependency> 
      <groupId>org.slf4j</groupId>  
      <artifactId>slf4j-api</artifactId>  
      <version>1.7.25</version> 
    </dependency>
    

    服务类

    共享文件操作类:

    • 使用@Async注解标注uploadSmbFileAsync方法和downloadSmbFileAsync方法为需要异步执行的方法。
    • 建议将jcifs.smb.client.dfs.disabled属性设置为true,默认值为false,在非域环境中,此属性可能很重要,其中基于域的DFS引用通常在JCIFS首次尝试解析路径时运行,这将导致超时,从而导致长启动延迟。
    package com.example.smb.service;
    /**
     * @author: 博客「成猿手册」
     * @description: 对共享文件的操作
     * @date: 2020/3/24
     */
    @Component
    public class SmbFileOperator {
        private final Logger logger = LoggerFactory.getLogger(SmbFileOperator.class);
    
        public SmbFileOperator() {
            System.setProperty("jcifs.smb.client.dfs.disabled", "true");
        }
    
        @Async
        public Future<String> uploadSmbFileAsync(File file, SmbFile smbFile) throws IOException {
            this.uploadSmbFile(file, smbFile);
            return new AsyncResult<>(smbFile.getPath());
        }
    
        @Async
        public Future<String> 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规避多线程访问出现线程不安全的方法:每个线程通过ThreadLocalset()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<List<SmbFileTask>> 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<Future<String>> futures = new ArrayList<>();
            try {
                generateDownloadSmbFileTask(smbFile, smbInfo, smbInfo.getLocalDirPath(), 1);
                List<SmbFileTask> tasks = smbFileTaskThreadLocal.get();
                Date begindate = new Date();
                for (SmbFileTask smbFileTask : tasks) {
                    //将线程储存类ThreadLocal内的多个任务全都通过异步下载方法执行
                    Future<String> future = smbFileOperator.downloadSmbFileAsync(smbFileTask.getFile(), smbFileTask.getSmbFile());
                    futures.add(future);
                }
                for (Future<String> 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<Future<String>> futures = new ArrayList<>();
            try {
                NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(smbInfo.getIp(),smbInfo.getUserName(),smbInfo.getPassWord());
                generateUploadSmbFileTask(file, smbInfo, smbFile.getURL().toString() + file.getName(),auth);
                List<SmbFileTask> tasks = smbFileTaskThreadLocal.get();
                Date begindate = new Date();
                for (SmbFileTask smbFileTask : tasks) {
                    //将线程储存类ThreadLocal内的多个任务全都通过异步下载方法执行
                    Future<String> future = smbFileOperator.uploadSmbFileAsync(smbFileTask.getFile(), smbFileTask.getSmbFile());
                    futures.add(future);
                }
                for (Future<String> 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<Future<String>> futures) {
            for (Future<String> 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
     */
    @Component
    public 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
     */
    @Component
    public 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
     */
    @Component
    public 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);
        }
    }
    
  • 相关阅读:
    ParallelsDesktop在windows 10虚拟机重启后分辨率无法保存的问题解决方案
    Windows10 2021年5月功能更新(21H1)的三种方式
    Database "mem:XXX" not found, either pre-create it or allow remote database creation (not recommended in secure environments) [90149-200] 90149/90149 解决方案
    Win7/8下提示OpenSCManager failed 拒绝访问 解决方案
    将 Windows 更新代理更新到最新版本
    解决Eclipse中无法直接使用sun.misc.BASE64Encoder及sun.misc.BASE64Decoder的问题
    【Windows】U 盘装系统,无法格式化所选磁盘分区[错误: 0x8004242d]解决方案
    Boot Camp列表-苹果电脑Windows驱动下载
    selenium4 Timeouts is deprecated
    Selenium4实践1——对比Selenium3,Selenium4更新了什么?
  • 原文地址:https://www.cnblogs.com/WangJpBlog/p/12773594.html
Copyright © 2020-2023  润新知