概述
依赖
<!--sFTP连接-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
import com.jcraft.jsch.*;
连接 使用ThreadLocal管理channel,确保每个线程单独一份channel,互不干扰
/**
* 登陆SFTP服务器
*
* @return boolean
*/
public static boolean isFtpConn = false;
/**
* Session
*/
private Session session = null;
/**
* Channel
*/
private ChannelSftp channel = null;
@PostConstruct
public boolean login() {
try {
JSch jsch = new JSch();
session = jsch.getSession(username, host, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(16000);
log.info(session.getHost() + session.getPort() + session.toString());
session.connect();
log.debug("sftp session connected");
log.debug("opening channel");
channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
log.info("connected successfully");
isFtpConn = true;
return true;
} catch (Exception e) {
isFtpConn = false;
log.info("sftp login failed", e);
return false;
}
}
//ThreadLocal在每个线程中对连接会创建一个副本,且在线程内部任何地方都可以使用,线程之间互不影响
private static ThreadLocal<ChannelSftp> t = new ThreadLocal<ChannelSftp>();
public ChannelSftp getChannel() throws JSchException {
ChannelSftp channel = t.get();
if (channel == null){
channel = (ChannelSftp) this.session.openChannel("sftp");
channel.connect();
t.set(channel);
}
return channel;
}
/**
* 关闭连接
* @param channel
*/
public static void closeResource(ChannelSftp channel) {
if (channel != null) {
channel.disconnect();
t.remove();
}
}
下载
public void downloadFile(String sourcePath, List<String> fileNameList, String descPath) throws RuntimeException {
if (!isFtpConn) {
if (!login()){
throw new RuntimeException("login failed");
}
}
ChannelSftp channel = null;
try {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (String fileName : fileNameList) {
String localFilePath = descPath + "/" + fileName;
Files.createDirectories(Paths.get(descPath));
channel = getChannel();
channel.get(localFilePath, localFilePath);
}
log.info("download successful ==== descPath ===" + descPath);
} catch (SftpException | IOException | JSchException e) {
log.info("download file failed", e);
throw new RuntimeException("download file failed");
} finally {
closeResource(channel);
}
}
jmeter压测
channel.get(sourcePath+fileName,descPath+fileName)为下载方法,可参考
https://www.cnblogs.com/longyg/archive/2012/06/25/2561332.html
不明白为什么好多人都要cd到当前目录,在根据当前目录get下载
最后
以上就是勤恳天空为你收集整理的单session多channel的sftp多线程并发下载的全部内容,希望文章能够帮你解决单session多channel的sftp多线程并发下载所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复