項目中需要用Sftp上傳下載下傳檔案,通過jsch中的sftp實作。代碼上了伺服器之後,發覺伺服器多了很多程序沒有被關閉。
連接配接sftp代碼:
protected boolean connectToServer() {
try {
JSch jsch = new JSch();
jsch.getSession(userName, hostname, port);
Session sshSession = jsch.getSession(userName, hostname, port);
logger.debug("HostName:" + hostname + "|Port:" + port);
logger.debug("Session created");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.setTimeout(TIMEOUT); //ms
sshSession.connect();
sftp = (ChannelSftp) sshSession.openChannel("sftp");
sftp.connect();
if (!sftp.isConnected()) {
logger.error("Failed to connect FTP server " + hostname);
return false;
}
logger.debug("Username:" + userName + "|Password:" + password);
} catch (Exception ex) {
logger.error(ex);
}
return true;
}
其實每次執行完都會
sftp.quit();
sftp.disconnet();
但是程序還是在,後來覺得應該是session沒有關閉。後來證明的确是這樣的,雖然sftp退出了,但是session還是存在的。解決辦法很簡單,隻要在sftp.quit() 之前加上 sftp.getSession().disconnect() 就可以了。