Browse Source

sftp文件上传保存一版

xusonglin 5 years ago
parent
commit
c21029d9d6

+ 2 - 2
src/main/java/com/jkcredit/asychronous/job/CarJob.java

@@ -30,8 +30,8 @@ public class CarJob {
     private Integer port;
     private Integer port;
     @Value("${ftp.username}")
     @Value("${ftp.username}")
     private String userName;
     private String userName;
-    @Value("${ftp.password}")
-    private String passWord;
+    @Value("${ftp.passphrase}")
+    private String passphrase;
     @Value("${ftp.dir.car}")
     @Value("${ftp.dir.car}")
     private String dir;
     private String dir;
 
 

+ 14 - 16
src/main/java/com/jkcredit/asychronous/job/ManJob.java

@@ -1,11 +1,10 @@
 package com.jkcredit.asychronous.job;
 package com.jkcredit.asychronous.job;
 
 
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONArray;
-import com.jkcredit.asychronous.common.ResponseEntity;
 import com.jkcredit.asychronous.entity.Man;
 import com.jkcredit.asychronous.entity.Man;
 import com.jkcredit.asychronous.service.ManService;
 import com.jkcredit.asychronous.service.ManService;
 import com.jkcredit.asychronous.util.ExcelUtil;
 import com.jkcredit.asychronous.util.ExcelUtil;
-import com.jkcredit.asychronous.util.FtpUtil;
+import com.jkcredit.asychronous.util.SFTPUtil;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.beans.factory.annotation.Value;
@@ -33,20 +32,21 @@ public class ManJob {
     private Integer port;
     private Integer port;
     @Value("${ftp.username}")
     @Value("${ftp.username}")
     private String userName;
     private String userName;
-    @Value("${ftp.password}")
-    private String passWord;
+    @Value("${ftp.passphrase}")
+    private String passphrase;
     @Value("${ftp.dir.man}")
     @Value("${ftp.dir.man}")
     private String dir;
     private String dir;
+    @Value("${ftp.keyFilePath}")
+    private String keyFilePath;
 
 
     @Autowired
     @Autowired
     private ManService manService;
     private ManService manService;
 
 
     @Scheduled(cron = "0/10 * * * * ?")
     @Scheduled(cron = "0/10 * * * * ?")
-    public void car() {
+    public void man() {
         Long beginTime= System.currentTimeMillis() - 10000;
         Long beginTime= System.currentTimeMillis() - 10000;
         Long endTime = System.currentTimeMillis();
         Long endTime = System.currentTimeMillis();
         List<Man> list = manService.selectByTime(beginTime,endTime);
         List<Man> list = manService.selectByTime(beginTime,endTime);
-//        log.info("开始 公安不良excel 导出");
         if (list.size() > 0) {
         if (list.size() > 0) {
             JSONArray ja = new JSONArray();
             JSONArray ja = new JSONArray();
             for(Man man : list){
             for(Man man : list){
@@ -57,27 +57,25 @@ public class ManJob {
             headMap.put("name","姓名");
             headMap.put("name","姓名");
             headMap.put("idCard","身份证号");
             headMap.put("idCard","身份证号");
             String fileName = localDir + File.separator + endTime.toString() + ".xlsx";
             String fileName = localDir + File.separator + endTime.toString() + ".xlsx";
-            // todo 异常 系统找不到路径
             try {
             try {
                 OutputStream outXlsx = new FileOutputStream(fileName);
                 OutputStream outXlsx = new FileOutputStream(fileName);
                 ExcelUtil.exportExcelX(headMap,ja,null,0,outXlsx);
                 ExcelUtil.exportExcelX(headMap,ja,null,0,outXlsx);
                 outXlsx.close();
                 outXlsx.close();
             } catch (FileNotFoundException e) {
             } catch (FileNotFoundException e) {
                 e.printStackTrace();
                 e.printStackTrace();
+                log.info("FileNotFoundException找不到路径");
             } catch (IOException e) {
             } catch (IOException e) {
                 e.printStackTrace();
                 e.printStackTrace();
             }
             }
-//            String fileName = ExcelUtil.export(list, Man.class, localDir,endTime.toString());
-//            log.info("ManExcel:{}", fileName);
-            FtpUtil.fileUpload(host, port, userName, passWord, dir, fileName);
+            try {
+                SFTPUtil.upload(host, port, userName, passphrase, File.separator + dir + File.separator +  endTime.toString() + ".xlsx", fileName, keyFilePath);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
         }
         }
-//        else {
-//            log.error("error:{}1", new ResponseEntity(400, "公安不良信息未查到", ""));
-//        }
-
     }
     }
 
 
-    //@Scheduled(cron = "0 0/30 * * * ?")
+    @Scheduled(cron = "0 19 16 * * ?", zone = "Asia/Shanghai")
     public void test(){
     public void test(){
 
 
         SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
         SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
@@ -107,6 +105,6 @@ public class ManJob {
         }
         }
 //            String fileName = ExcelUtil.export(list, Man.class, localDir,endTime.toString());
 //            String fileName = ExcelUtil.export(list, Man.class, localDir,endTime.toString());
 //            log.info("ManExcel:{}", fileName);
 //            log.info("ManExcel:{}", fileName);
-        FtpUtil.fileUpload(host, port, userName, passWord, dir, fileName);
+//        SFTPUtil.upload(host, port, userName, passphrase, dir, fileName);
     }
     }
 }
 }

+ 102 - 0
src/main/java/com/jkcredit/asychronous/util/SFTPUtil.java

@@ -0,0 +1,102 @@
+package com.jkcredit.asychronous.util;
+
+import com.jcraft.jsch.ChannelSftp;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.Session;
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.*;
+import java.text.SimpleDateFormat;
+import java.util.Properties;
+
+/**
+ * @description:
+ * @author: xusonglin
+ * @create: 2020/2/3 17:19
+ * @version: V1.0
+ **/
+@Slf4j
+public class SFTPUtil {
+    static JSch jsch = null;
+    static Session session = null;
+    static ChannelSftp channel = null;
+
+    /**
+     * 密钥连接到指定的IP
+     *
+     * @param keyFilePath 密钥路径
+     * @param passphrase  密钥的密码
+     */
+    public static void connect(String userName, String host, int port, String passphrase, String keyFilePath) throws Exception {
+        try {
+            jsch = new JSch();
+            if (keyFilePath != null) {
+                if (passphrase != null) {
+                    jsch.addIdentity(keyFilePath, passphrase);// 设置私钥
+                } else {
+                    jsch.addIdentity(keyFilePath);// 设置私钥
+                }
+                log.info("连接sftp,私钥文件路径:" + keyFilePath);
+            }
+            log.info("SFTP Host: " + host + "; UserName:" + userName);
+            session = jsch.getSession(userName, host, port);
+            log.debug("Session 已建立.");
+            Properties sshConfig = new Properties();
+            sshConfig.put("StrictHostKeyChecking", "no");
+            session.setConfig(sshConfig);
+            session.setConfig("kex", "diffie-hellman-group1-sha1");
+            session.connect();
+            log.debug("Session 已连接.");
+            channel = (ChannelSftp) session.openChannel("sftp");
+            channel.connect(60000);
+            log.info("连接到SFTP成功.Host: " + host);
+        } catch (Exception e) {
+            log.error("连接SFTP失败:", e);
+        }
+    }
+
+    /**
+     * 关闭连接
+     */
+    private static void close() {
+        if (channel != null) {
+            try {
+                channel.disconnect();
+            } catch (Exception e) {
+                log.error("sftp close channel failed...", e);
+            }
+        }
+        if (session != null) {
+            try {
+                session.disconnect();
+            } catch (Exception e) {
+                log.error("sftp close session failed...", e);
+            }
+        }
+    }
+
+    public static void upload(String host, Integer port, String userName, String passphrase, String dir,String fileName, String keyFilePath) throws Exception {
+        //连接sftp
+        connect(userName, host, port, passphrase, keyFilePath);
+        if (channel == null) {
+            log.info("SFTP服务器未连接");
+            return;
+        }
+        try {
+//            fileName = "C:\\Users\\Administrator\\Desktop\\ftp\\upload\\1580697240002.xlsx";
+//            channel.put(new FileInputStream(fileName), "/download/1580697240002.xlsx", ChannelSftp.OVERWRITE);
+            log.info("dis == " + dir);
+            channel.put(new FileInputStream(fileName), dir, ChannelSftp.OVERWRITE);
+            log.info("上传到sftp成功");
+        } catch (Exception e) {
+            log.info("上传文件:" + fileName + "失败");
+            throw e;
+        } finally {
+            close();
+        }
+
+        // todo 秘钥文件路径有问题 需要测试上传  下载需要在util中写个方法,替换ftp文件夹下的route
+    }
+
+
+}