Spring boot FTP 连接池上传,批量上传,ftpClient 上传,支持多连接快速切换上传
1.引入jar
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.8.0</version>
</dependency>
2. FTP 配置
ftp:
ftpServer0:
hostname: localhost
port: 21
username: guest
password: b_27Fir#MwA@Rei_nfO
encoding: UTF-8
ftpServer1:
hostname: localhost
port: 21
username: guest
password: b_27Fir#MwA@Rei_nfO
encoding: UTF-8
3. 读取配置
@Component
@ConfigurationProperties(prefix = "ftp")
public class FTPProperties {
private FtpServer ftpServer0 = new FtpServer();
private FtpServer ftpServer1 = new FtpServer();
@Data
public class FtpServer {
private String hostname;
private Integer port;
private String username;
private String password;
/**
* 编码
*/
private String encoding;
}
}
4. 添加springboot 配置,注册bean
@Configuration
@EnableConfigurationProperties(FTPProperties.class)
public class FTPConfig {
}
5. 创建 FTPClient 工厂
@Slf4j
public class FTPClientFactory extends BasePooledObjectFactory<FTPClient> {
public FTPProperties.FtpServer ftpServer;
public FTPClientFactory(FTPProperties.FtpServer ftpServer) {
this.ftpServer = ftpServer;
}
@Override
public FTPClient create() throws Exception {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftpServer.getHostname(), ftpServer.getPort());
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
ftpClient.disconnect();
log.warn("FTP服务器拒绝连接");
return null;
}
log.info("连接FTP服务器成功返回码 ==> {}", ftpClient.getReplyCode());
ftpClient.login(ftpServer.getUsername(), ftpServer.getPassword());
log.info("登录FTP服务器成功返回码 ==> {}", ftpClient.getReplyCode());
ftpClient.enterLocalPassiveMode();
return ftpClient;
}
/**
* 用PooledObject封装对象放入池中
* @param ftpClient
* @return
*/
@Override
public PooledObject<FTPClient> wrap(FTPClient ftpClient) {
return new DefaultPooledObject<>(ftpClient);
}
/**
* 销毁
* @param ftpPooled
* @