相关依赖引入:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
sftp连接池工具代码:
package com.example.rdemo.util;
import com.jcraft.jsch.*;
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.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
/**
* @author admin
*/
public class SftpConnectPoolUtil {
private final static Logger log = LoggerFactory.getLogger(SftpConnectPoolUtil.class);
/**
* SFTP
*/
public static final String SFTP = "sftp";
/**
* 通道
*/
private ChannelSftp channel;
/**
* session
*/
private Session session;
/**
* 规避多线程并发不断开问题
*/
private static ThreadLocal<SftpConnectPoolUtil> sftpLocal = new ThreadLocal<SftpConnectPoolUtil>();
/**
* 获取sftpchannel
*
* @param host 主机
* @param port 端口
* @param username 用户名
* @param password 密码
* @return
* @throws Exception
*/
private void init(String port, String host, String username, String password) throws Exception {
//创建JSch对象
JSch jsch = new JSch();
session = jsch.getSession(username, host, Integer.parseInt(port));
System.out.println("Session created.");
//设置密码
if (!StringUtils.isEmpty(password)) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
config.put("UseDNS", "no");
session.setConfig(config);
//设置超时
session.setTimeout(3000);
//建立连接
session.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
//打开SFTP通道
channel = (ChannelSftp) session.openChannel(SFTP);
//建立SFTP通道的连接
channel.connect();
}
/**
* 是否已连接
*
* @return
*/
private boolean isConnected() {
return null != channel && channel.isConnected();
}
/**
* 获取本地线程存储的sft