基于spring boot sftp文件上传

基于spring boot sftp文件上传

2018年06月21日 11:30:17 奇点_ 阅读数 3101

对sftp文件上传将行封装,实现连接的单例模式,完成线程安全的改进,sftp文件上传下载失败的重试。

application.yml配置文件

 

 
  1. sftp:

  2.    ip: 192.168.43.102

  3.    port: 22

  4.    username: admin

  5.    password: admin

  6.    downloadSleep: 100 #文件下载失败下次超时重试时间

  7.    downloadRetry: 10 #文件下载失败重试次数

  8.    uploadSleep: 100 #文件上传失败下次超时重试时间

  9.    uploadRettry: 10 #文件上传失败重试次数

SFTPClientUtils.java

包含sftp文件上传的一些基本方法,单个上传,批量下载,单个文件下载

 
  1. @Component

  2. @ConfigurationProperties(prefix = "sftp")

  3. public class SFTPClientUtils {

  4. private static int downloadSleep;

  5. private static int downloadRetry;

  6. private static int uploadSleep;

  7. private static int uploadRettry;

  8. private static Logger LOGGER = LoggerFactory.getLogger(SFTPClientUtils.class);

  9. /** 

  10. * 文件上传  

  11.      * 将文件对象上传到sftp作为文件。文件完整路径=basePath+directory

  12.      * 目录不存在则会上传文件夹 

  13.      * @param basePath  服务器的基础路径  

  14.      * @param directory  上传到该目录   

  15.      * @param sftpFileName  sftp端文件名   

  16.      * @param file   文件对象   

  17.      */    

  18.     public synchronized static boolean upload(String basePath,String directory, String filePath){    

  19.     boolean result = false;

  20.     Integer i = 0;

  21.         while(!result){

  22.         ChannelSftp sftp = SFTPConnectionFactory.getInstance().makeConnection();

  23.         try {     

  24.                 sftp.cd(basePath);  

  25.                 sftp.cd(directory);    

  26.             } catch (SftpException e) {   

  27.             LOGGER.info("sftp文件上传,目录不存在开始创建");

  28.                 String [] dirs=directory.split("/");  

  29.                 String tempPath=basePath;  

  30.                 for(String dir:dirs){  

  31.                     if(null== dir || "".equals(dir)) continue;  

  32.                     tempPath+="/"+dir;  

  33.                     try{   

  34.                         sftp.cd(tempPath);  

  35.                     }catch(SftpException ex){  

  36.                         try {

  37.     sftp.mkdir(tempPath);

  38.     sftp.cd(tempPath);  

  39.     } catch (SftpException e1) {

  40.     LOGGER.error("sftp文件上传,目录创建失败,错误信息:"+e1.getMessage()+ex.getMessage());

  41.     }  

  42.                     }  

  43.                 }  

  44.             }    

  45.             try {

  46.             File file = new File(filePath);

  47.     sftp.put(new FileInputStream(file) , file.getName());

  48.     if(i>0){

  49. LOGGER.info("sftp重试文件上传成功,ftp路径:"+basePath+directory+",文件名称:"+file.getName());

  50. }else{

  51. LOGGER.info("sftp文件上传成功,ftp路径为"+basePath+directory+",文件名称:"+file.getName());

  52. }

  53.     result = true;

  54.     } catch (Exception e) {

  55.     i++;

  56.     LOGGER.error("sftp文件上传失败,重试中。。。第"+i+"次,错误信息"+e.getMessage());

  57. if(i>uploadRettry){

  58. LOGGER.error("sftp文件上传失败,超过重试次数结束重试,错误信息"+e.getMessage());

  59. return result;

  60. }

  61.     try {

  62. TimeUnit.MILLISECONDS.sleep(uploadSleep);

  63. } catch (InterruptedException e1) {

  64. e1.printStackTrace();

  65. }

  66.     }  

  67.             

  68.         }

  69.    

  70.         return result;

  71.     }   

  72.     /**  

  73.      * 下载文件。 

  74.      * @param directory 下载目录   

  75.      * @param downloadFile 下载的文件  

  76.      * @param saveFile 存在本地的路径  

  77.      */      

  78.     public synchronized static boolean download(String directory, String downloadFile, String saveFile){    

  79.     boolean result = false;

  80.     Integer i = 0;

  81.     while(!result){

  82.     ChannelSftp sftp = SFTPConnectionFactory.getInstance().makeConnection();

  83.     if (directory != null && !"".equals(directory)) {    

  84.     try {

  85.     sftp.cd(directory);

  86.     } catch (SftpException e) {

  87.     LOGGER.error("sftp文件下载,目录不存在,错误信息"+e.getMessage());

  88.     }    

  89.     }    

  90.     File file = new File(saveFile+downloadFile); 

  91.     FileOutputStream fileOutputStream = null;

  92.     try {

  93.     fileOutputStream = new FileOutputStream(file);

  94.     } catch (FileNotFoundException e1) {

  95.     LOGGER.error("sftp文件下载失败,本地目录不存在"+e1.getMessage());

  96.     }

  97.     try {

  98.     sftp.get(downloadFile, fileOutputStream);

  99. if(i>0){

  100.     LOGGER.info("sftp文件重试下载成功,sftp地址:"+directory+",本地文件地址:"+saveFile);

  101.     }else{

  102.     LOGGER.info("sftp文件下载成功,sftp地址:"+directory+",本地文件地址:"+saveFile);

  103.     }

  104.     result = true;

  105.     } catch (SftpException e1) {

  106.     i++;

  107. LOGGER.error("sftp文件下载失败,重试中。。。第"+i+"次,错误信息"+e1.getMessage());

  108. if(i>downloadRetry){

  109. LOGGER.error("ftp文件下载失败,超过重试次数结束重试,错误信息"+e1.getMessage());

  110. return result;

  111. }

  112. try {

  113. TimeUnit.MILLISECONDS.sleep(downloadSleep);

  114. } catch (Exception e2) {

  115. e2.printStackTrace();

  116. }

  117.     }finally {

  118.     try {

  119.     fileOutputStream.close();

  120.     } catch (IOException e) {

  121.    

  122.     e.printStackTrace();

  123.     }

  124.     }

  125.     }

  126.         return result;

  127.     }    

  128.     

  129.       

  130.       

  131.     /**  

  132.      * 删除文件  

  133.      * @param directory 要删除文件所在目录  

  134.      * @param deleteFile 要删除的文件  

  135.      */    

  136.     public synchronized static boolean delete(String directory, String deleteFile){    

  137.     boolean result = false;

  138.     ChannelSftp sftp = SFTPConnectionFactory.getInstance().makeConnection();

  139.     try {

  140. sftp.cd(directory);

  141. sftp.rm(deleteFile);

  142. } catch (SftpException e) {

  143. // TODO Auto-generated catch block

  144. e.printStackTrace();

  145. }    

  146.         result = true;

  147.         return result;

  148.     }

  149. public static int getDownloadSleep() {

  150. return downloadSleep;

  151. }

  152. public static void setDownloadSleep(int downloadSleep) {

  153. SFTPClientUtils.downloadSleep = downloadSleep;

  154. }

  155. public static int getDownloadRetry() {

  156. return downloadRetry;

  157. }

  158. public static void setDownloadRetry(int downloadRetry) {

  159. SFTPClientUtils.downloadRetry = downloadRetry;

  160. }

  161. public static int getUploadSleep() {

  162. return uploadSleep;

  163. }

  164. public static void setUploadSleep(int uploadSleep) {

  165. SFTPClientUtils.uploadSleep = uploadSleep;

  166. }

  167. public static int getUploadRettry() {

  168. return uploadRettry;

  169. }

  170. public static void setUploadRettry(int uploadRettry) {

  171. SFTPClientUtils.uploadRettry = uploadRettry;

  172. }    

  173.       

  174.       

  175.    

  176.         

  177.    

  178. }

SFTPConnectionFactory.java

是生成sftp上传对象的工场类

 
  1. /**

  2.  * SFTP工厂类,用于获取SFTP的连接

  3.  * @author 奇点_

  4.  */

  5. @Component

  6. @ConfigurationProperties(prefix = "sftp")

  7. public class SFTPConnectionFactory {

  8. private static Logger LOGGER = LoggerFactory.getLogger(FTPClientUtils.class);

  9.     /** SFTP 登录用户名*/      

  10.     private static String username;   

  11.     /** SFTP 登录密码*/      

  12.     private static String password;    

  13.     /** 私钥 */      

  14.     private static String privateKey;    

  15.     /** SFTP 服务器地址IP地址*/      

  16.     private static String ip;    

  17.     /** SFTP 端口*/    

  18.     private static int port;

  19.  
  20. private static final SFTPConnectionFactory factory = new SFTPConnectionFactory();

  21. private ChannelSftp client;

  22. private Session session;

  23. private SFTPConnectionFactory(){

  24.  
  25. }

  26.  
  27. public static SFTPConnectionFactory getInstance(){

  28. return factory;

  29. }

  30. synchronized public ChannelSftp makeConnection(){

  31.  
  32. if(client==null||session==null||!client.isConnected()||!session.isConnected()){

  33. try {    

  34. JSch jsch = new JSch();    

  35. if (privateKey != null) {    

  36. jsch.addIdentity(privateKey);// 设置私钥    

  37. }    

  38. session = jsch.getSession(username, ip, port);    

  39. if (password != null) {    

  40. session.setPassword(password);      

  41. }    

  42. Properties config = new Properties();    

  43. config.put("StrictHostKeyChecking", "no");    

  44. session.setConfig(config);    

  45. session.connect();    

  46. Channel channel = session.openChannel("sftp");    

  47. channel.connect();    

  48. client = (ChannelSftp) channel;    

  49. LOGGER.info("sftp服务器连接成功");

  50. } catch (JSchException e) {    

  51. LOGGER.error("sftp登录失败,检测登录ip,端口号,用户名密码是否正确,错误信息为"+e.getMessage());

  52. }

  53.     

  54.      return client;

  55. }

  56. /**  

  57.      * 关闭连接 server   

  58.      */    

  59.     public  void logout(){    

  60.         if (client != null) {    

  61.             if (client.isConnected()) {    

  62.             client.disconnect();    

  63.             }    

  64.         }    

  65.         if (session != null) {    

  66.             if (session.isConnected()) {    

  67.                 session.disconnect();    

  68.             }    

  69.         }    

  70.     }

  71.  
  72.  
  73. public static String getUsername() {

  74. return username;

  75. }

  76.  
  77.  
  78. public static void setUsername(String username) {

  79. SFTPConnectionFactory.username = username;

  80. }

  81.  
  82.  
  83. public static String getPassword() {

  84. return password;

  85. }

  86.  
  87.  
  88. public static void setPassword(String password) {

  89. SFTPConnectionFactory.password = password;

  90. }

  91.  
  92.  
  93. public static String getPrivateKey() {

  94. return privateKey;

  95. }

  96.  
  97.  
  98. public static void setPrivateKey(String privateKey) {

  99. SFTPConnectionFactory.privateKey = privateKey;

  100. }

  101.  
  102.  
  103. public static String getIp() {

  104. return ip;

  105. }

  106.  
  107.  
  108. public static void setIp(String ip) {

  109. SFTPConnectionFactory.ip = ip;

  110. }

  111.  
  112.  
  113. public static int getPort() {

  114. return port;

  115. }

  116.  
  117.  
  118. public static void setPort(int port) {

  119. SFTPConnectionFactory.port = port;

  120. }

  121. }

pom.xml 依赖

 
  1. <dependencies>

  2. <dependency>

  3. <groupId>org.springframework.boot</groupId>

  4. <artifactId>spring-boot-starter-web</artifactId>

  5. </dependency>

  6. <dependency>

  7. <groupId>fakepath</groupId>

  8. <artifactId>ftp4j</artifactId>

  9. <version>1.7.2</version>

  10. </dependency>

  11. <dependency>

  12. <groupId>com.jcraft</groupId>

  13. <artifactId>jsch</artifactId>

  14. <version>0.1.54</version>

  15. </dependency>

  16. <dependency>

  17. <groupId>org.springframework.boot</groupId>

  18. <artifactId>spring-boot-configuration-processor</artifactId>

  19. <optional>true</optional>

  20. </dependency>

  21. </dependencies>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值