springbootスレッド池接続sftpアップロードファイル

38034 ワード

springbootはsftpで接続してアップロードします.
  • springbootでは、スレッドを使ってsftpを接続してファイルをアップロードする
  • springbootでスレッドを使ってsftpを接続してファイルをアップロードします.
    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    import com.jcraft.jsch.SftpATTRS;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.StringUtils;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.util.Date;
    
    
    public class sftp {
        private static final Logger logger = LoggerFactory.getLogger(sftp.class);
    
        private static Date last_push_date = null;
    
        private Session sshSession;
    
        private ChannelSftp channel;
    
        private static ThreadLocal<sftp> sftpLocal = new ThreadLocal<sftp>();
    
    
        public static void main(String[] args) throws Exception {
            new Thread() {
                @Override
                public void run() {
                    try {
                        sftp.getSftpUtil("x.x.x.x", 22, "root", "root");
                        File file = new File("C:\\Users\\zheng\\Desktop\\2.png");
                        InputStream inputStream = new FileInputStream(file);
                        sftp.uploadFile("/home/web", "/moregs-oss/test", inputStream, "2.png");
                        sftp.release();
                        System.out.println("1111" + sftpLocal.get());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
    
            //  2 ThreadLocalMap   key threadLocalA,value A2;key threadLocalB,value B2
            new Thread() {
                @Override
                public void run() {
                    try {
                        sftp.getSftpUtil("x.x.x.x", 22, "root", "root");
    
                        File file = new File("C:\\Users\\zheng\\Desktop\\1.png");
                        InputStream inputStream = new FileInputStream(file);
                        sftp.uploadFile("/home/web", "/moregs-oss/test", inputStream, "1.png");
                        sftp.release();
                        System.out.println("2222" + sftpLocal.get());
    
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
    
    
                }
            }.start();
        }
    
    
        private sftp(String host, int port, String username, String password) throws Exception {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            //     ,  ,     session
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            //     /etc/ssh/sshd_config   GSSAPIAuthentication  yes no,          
            sshSession.setConfig("userauth.gssapi-with-mic", "no");
    
            // session    properties,             yes
            sshSession.setConfig("StrictHostKeyChecking", "no");
            sshSession.connect();
            //  sftp  
            channel = (ChannelSftp) sshSession.openChannel("sftp");
            channel.connect();
            logger.info("  ftp  !" + sshSession);
        }
    
        /**
         *      
         *
         * @return
         */
        private boolean isConnected() {
            return null != channel && channel.isConnected();
        }
    
        /**
         *          sftp   
         *
         * @return
         * @throws Exception
         */
        public static sftp getSftpUtil(String host, int port, String username, String password) throws Exception {
            //      
            sftp sftpUtil = sftpLocal.get();
            if (null == sftpUtil || !sftpUtil.isConnected()) {
                //          ,      
                sftpLocal.set(new sftp(host, port, username, password));
            }
            return sftpLocal.get();
        }
    
        /**
         *          sftp   
         */
        public static void release() {
            if (null != sftpLocal.get()) {
                sftpLocal.get().closeChannel();
                logger.info("    " + sftpLocal.get().sshSession);
                sftpLocal.set(null);
                sftpLocal.remove();
            }
        }
    
        /**
         *         
         */
        private static boolean isDirExist(String directory) {
            boolean isDirExistFlag = false;
            try {
                SftpATTRS sftpATTRS = sftpLocal.get().channel.lstat(directory);
                isDirExistFlag = true;
                return sftpATTRS.isDir();
            } catch (Exception e) {
                if ("no such file".equals(e.getMessage().toLowerCase())) {
                    isDirExistFlag = false;
                }
            }
            return isDirExistFlag;
        }
    
        /**
         *         
         */
        private static void createDir(String createpath) throws Exception {
            if (!isDirExist(createpath)) {
                String pathArry[] = createpath.split("/");
    
                for (String path : pathArry) {
                    if (StringUtils.isEmpty(path)) {
                        continue;
                    }
                    if (isDirExist(path)) {
                        sftpLocal.get().channel.cd(path);
                    } else {
                        //     
                        sftpLocal.get().channel.mkdir(path);
                        //           
                        sftpLocal.get().channel.cd(path);
                    }
                }
            }
        }
    
    
        /**
         *     
         *
         * @throws Exception
         */
        public static void closeChannel() {
            if (null != sftpLocal.get().channel && sftpLocal.get().channel.isConnected()) {
                try {
                    sftpLocal.get().channel.disconnect();
                } catch (Exception e) {
                    logger.error("  SFTP      :", e);
                }
            }
            if (null != sftpLocal.get().sshSession && sftpLocal.get().sshSession.isConnected()) {
                try {
                    sftpLocal.get().sshSession.disconnect();
                } catch (Exception e) {
                    logger.error("SFTP   session  :", e);
                }
            }
        }
    
        /**
         *     (cd       ,  cd   cd           )
         *
         * @param directory   ftp   
         * @param input         InputStream
         */
        public static boolean uploadFile(String basePath, String directory, InputStream input, String fileName) {
            //    
            try {
                sftpLocal.get().channel.cd(basePath);
    
                createDir(directory);
    
                sftpLocal.get().channel.put(input, fileName);
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage() + e.getMessage() + e.toString());
                return false;
            }
            return true;
        }
    
    }
    
    <dependency>
    			<groupId>com.jcraft</groupId>
    			<artifactId>jsch</artifactId>
    			<version>0.1.49</version>
    		</dependency>