添加依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
增加配置
sftp:
ip: 192.168.1.60
port: 22
timeout: 60000
retryTime: 3
admin:
username: admin
password: 2k3xrYjbd930.
代码示例
每天凌晨1点在多个用户目录中下载csv文件至本地tmp目录
@Service
public class SftpTask extends Thread {
private ChannelSftp sftp;
private Session session;
@Value("${sftp.admin.username}")
private String username;
@Value("${sftp.admin.password}")
private String password;
@Value("${sftp.host}")
private String host;
@Value("${sftp.port}")
private Integer port;
private SftpService sftpService;
public EtlSftpTask (SftpService sftpService) {
this.sftpService = sftpService;
}
/**
* 建立sftp连接
*/
private void connect(){
try {
JSch jSch = new JSch();
session = jSch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
}catch (JSchException e) {
e.printStackTrace();
}
}
/**
* 关闭sftp连接
*/
public void close(){
try {
if (sftp != null) {
if (sftp.isConnected()) sftp.disconnect();
}
if(session != null){
if (session.isConnected()) session.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下载文件到本地
*
* @param source 源文件
* @param target 目标文件
* @throws SftpException 异常
* @throws FileNotFoundException 异常
*/
private void download(String source, String target) throws SftpException, FileNotFoundException {
sftp.get(source, new FileOutputStream(new File(target)));
}
/**
* 处理用户数据文件
*
* @param root 数据文件根目录
* @param lastTime 上次处理文件的最后的时间
* @return 本次处理文件的最后的时间
*/
private Integer handle(String root, Integer lastTime) {
String directory = root + "/event/";
Vector files;
try {
files = sftp.ls(directory + "event_*.csv");
} catch (Exception e) {
e.printStackTrace();
return 0;
}
String fileName;
String tmpFile;
Integer mTime;
Integer maxTime = lastTime;
for(Object o: files) {
try {
ChannelSftp.LsEntry f = (ChannelSftp.LsEntry) o;
mTime = f.getAttrs().getMTime();
if (mTime <= lastTime) continue;
fileName = f.getFilename();
maxTime = Math.max(maxTime, mTime);
tmpFile = "/tmp/" + fileName;
download(directory + fileName, tmpFile);
} catch (Exception e) {
e.printStackTrace();
}
}
return maxTime;
}
/**
* 每天凌晨1点开始执行
*/
@Scheduled(cron = "0 0 1 * * *")
public void task () {
connect();
String root;
Integer lastTime;
Long cid;
Integer maxTime = lastTime;
for (SftpDTO sftpDTO: sftpService.findAll()) {
root = sftpDTO.getSftpRoot();
lastTime = sftpDTO.getLastTime();
maxTime = Math.max(maxTime, handle(root, lastTime));
if (!maxTime.equals(lastTime)) {
sftpDTO.setLastTime(maxTime);
sftpService.update(sftpDTO);
}
}
close();
}
}