在有些項(xiàng)目組中碉就,會(huì)選擇使用SFTP做為文件存儲(chǔ)的服務(wù)器钳吟,最近我負(fù)責(zé)的一個(gè)系統(tǒng)接入公司的一個(gè)新系統(tǒng)手素。他們將生成的文件放在SFTP服務(wù)器滴铅,然后我要去SFTP去取文件戳葵。
SFTP搭建
想要在Linux系統(tǒng)中搭建SFTP服務(wù)還是很簡(jiǎn)單的。具體操作步驟請(qǐng)參考:SFTP服務(wù)搭建
SFTP集成
任何服務(wù)的繼承汉匙,都需要引入相關(guān)的依賴拱烁。JSCH為我們提供了Java操作SFTP的客戶端。首先我們需要在POM文件中引入jsch的依賴噩翠。
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
此外戏自,Spring也為我們提供了和SFTP的集成,其實(shí)也是對(duì)jsch的封裝伤锚,如果要使用Spring的封裝來(lái)和SFTP交互的話擅笔,需要引入下面的依賴
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-sftp</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
引入spring-integration-sftp
,它會(huì)間接依賴jsch屯援。不過(guò)這里我不打算使用Spring的封裝類來(lái)操作jsch猛们,而是通過(guò)其原生的API來(lái)操作。
自定義一個(gè)SFTP的工具類狞洋。
public class SftpUtil {
private static Logger logger = LoggerFactory.getLogger(SftpUtil.class);
private static ChannelSftp sftp = null;
private static Session sshSession = null;
/**
* 通過(guò)SFTP連接服務(wù)器
*/
private static void connect(SftpBean sftpBean) {
JSch jsch = new JSch();
Session session;
try {
if (sftpBean.getSftpHost()!=null) {
session = jsch.getSession(sftpBean.getSftpUser(), sftpBean.getSftpHost());
logger.info("連接sftp {}:{} 弯淘,用戶【{}】", new Object[] { sftpBean.getSftpHost(),
22, sftpBean.getSftpUser() });
} else {
session = jsch.getSession(sftpBean.getSftpUser(), sftpBean.getSftpHost(),
Integer.parseInt(sftpBean.getSftpPort()));
logger.info("連接sftp {}:{} ,用戶【{}】", new Object[] { sftpBean.getSftpHost(),
sftpBean.getSftpPort(), sftpBean.getSftpUser() });
}
if (sftpBean.getSftpPassword()!=null) {
session.setPassword(sftpBean.getSftpPassword());
}
session.setConfig("StrictHostKeyChecking", "no");
session.connect(300000);
logger.info("連接sftp {}:{} 成功", new Object[] { sftpBean.getSftpHost(), sftpBean.getSftpPort() });
Channel channel = session.openChannel("sftp");
// 建立SFTP通道的連接
channel.connect(10000);
sftp = (ChannelSftp) channel;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 關(guān)閉連接
*/
public static void disconnect(){
if (sftp != null && sftp.isConnected()) {
try {
// 要想關(guān)閉sftp的連接吉懊,注意一定要關(guān)閉ChannelSftp對(duì)象中的session
if (sftp.getSession() != null) {
sftp.getSession().disconnect();
}
} catch (JSchException e) {
e.printStackTrace();
}
sftp.disconnect();
}
if (sshSession != null && sshSession.isConnected()){
sshSession.disconnect();
}
}
public static InputStream getFileFromSFtp(SftpBean sftpBean, String fileName) throws SftpException {
connect(sftpBean);
try {
sftp.cd(sftpBean.getSftpPath());
} catch (Exception e) {
e.printStackTrace();
}
InputStream inputStream = sftp.get(fileName);
return inputStream;
}
public static void downloadFileFromSFtp(SftpBean sftpBean, String srcFile, String destFile) throws SftpException {
connect(sftpBean);
try {
sftp.cd(sftpBean.getSftpPath());
} catch (Exception e) {
e.printStackTrace();
}
sftp.get(srcFile,destFile);
}
public boolean uploadFile(String remotePath, String remoteFileName,String localPath, String localFileName){
try(FileInputStream in = new FileInputStream(new File(localPath + localFileName));) {
sftp.put(in, remoteFileName);
return true;
} catch (FileNotFoundException e){
e.printStackTrace();
}catch (SftpException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
注意:關(guān)閉連接的時(shí)候庐橙,一定要先關(guān)閉ChannelSftp
中的session對(duì)象
sftp.getSession().disconnect();
不然會(huì)產(chǎn)生一個(gè)現(xiàn)象:程序執(zhí)行完之后,連接依然不會(huì)斷開(kāi)借嗽。
一些常用的api方法:
put(): 文件上傳
get(): 文件下載
cd(): 進(jìn)入指定目錄
ls(): 得到指定目錄下的文件列表
rename(): 重命名指定文件或目錄
rm(): 刪除指定文件
mkdir(): 創(chuàng)建目錄
rmdir(): 刪除目錄
客戶端
public class SftpJavaApplication {
public static void main(String[] args){
// handleFileAllInMem();
// downloadFile();
handleFileWithBufferLoop();
}
private static void handleFileWithBufferLoop() {
System.out.println(Runtime.getRuntime().maxMemory()/1024/1024);
SftpBean sftpBean = new SftpBean("192.168.2.200", "mysftp", "mysftp", "/upload");
try(InputStream inputStream = SftpUtil.getFileFromSFtp(sftpBean, "Spitter.java");) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
System.out.println(inputStream.available());
String line = null;
while ((line=bufferedReader.readLine())!=null){
System.out.println(line);
// other handle (check date, insert DB)
}
} catch (Exception e){
e.printStackTrace();
} finally {
SftpUtil.disconnect();
System.out.println("關(guān)閉sftp服務(wù)器的連接");
}
}
private static void downloadFile() {
SftpBean sftpBean = new SftpBean("192.168.2.200", "mysftp", "mysftp", "/upload");
try {
SftpUtil.downloadFileFromSFtp(sftpBean, "Spitter.java","D:\\Test\\Test.txt");
} catch (Exception e){
e.printStackTrace();
} finally {
SftpUtil.disconnect();
System.out.println("關(guān)閉sftp服務(wù)器的連接");
}
}
private static void handleFileAllInMem() {
System.out.println(Runtime.getRuntime().maxMemory()/1024/1024);
SftpBean sftpBean = new SftpBean("192.168.2.200", "mysftp", "mysftp", "/upload");
SftpUtil sftpUtil = new SftpUtil();
InputStream inputStream = null;
BufferedReader bufferedReader = null;
try {
inputStream = SftpUtil.getFileFromSFtp(sftpBean, "Spitter.java");
//這里實(shí)現(xiàn)一次將流全加載到內(nèi)存中
byte[] bytes = getBytes(inputStream);
BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(bytes));
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
String line = null;
while((line = bufferedReader.readLine())!= null){
System.out.println(line);
}
} catch (Exception e){
e.printStackTrace();
} finally {
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
SftpUtil.disconnect();
System.out.println("關(guān)閉sftp服務(wù)器的連接");
}
}
private static byte[] getBytes(InputStream in) {
byte[] buffer = null;
try{
byte[] b = new byte[1024];
int n;
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
while ((n = in.read(b)) != -1) {
bos.write(b, 0, n);
}
buffer = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
}
handleFileAllInMem()
一次將文件的流全讀到流中怕午,這會(huì)產(chǎn)生內(nèi)存溢出。當(dāng)然如果能夠預(yù)知每次處理的文件都會(huì)不很大淹魄,那么這種寫法也沒(méi)有問(wèn)題郁惜。
downloadFile()
方法將文件下載到本地,不會(huì)產(chǎn)生內(nèi)存溢出的問(wèn)題甲锡。這種適合文件較大兆蕉,網(wǎng)絡(luò)不是很穩(wěn)定的情況。如果文件超大的話缤沦,我們可以使用多線程實(shí)現(xiàn)多點(diǎn)續(xù)傳的方式來(lái)加速虎韵。如果HTTP協(xié)議通過(guò)HttpUrlConnection很好實(shí)現(xiàn),不過(guò)SFTP暫時(shí)沒(méi)發(fā)現(xiàn)什么好的方法(如果你知道了缸废,煩請(qǐng)告訴我包蓝,讓我學(xué)習(xí)一下)驶社。
handleFileWithBufferLoop()
方法將網(wǎng)絡(luò)流每次處理一行,即每次加載一行到內(nèi)存测萎,這也能解決內(nèi)存溢出問(wèn)題亡电。但是如果存在網(wǎng)絡(luò)波動(dòng)的情況,此方式?jīng)]法很好的解決硅瞧。