spring集成:连接多个sftp服务器的解决方案/提示



我的spring-batch项目需要从多个sftp服务器下载文件。sftp host/port/filePath是application.properties文件中的config。我考虑使用spring集成"sftp出站网关"来连接这些服务器并下载文件。但我不知道如何进行这种配置(我使用的是javaconfig)并使其工作?我想我需要一些方法来根据application.properties文件中sftp服务器信息配置的数量定义多会话工厂。

属性文件:

sftp.host=host1,host2
sftp.user=user1,user2
sftp.pwd=pwd1,pwd2

配置类:

@Bean
public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory1() {
...
}
@Bean(name = "myGateway1")
@ServiceActivator(inputChannel = "sftpChannel1")
public MessageHandler handler1() {
...
}
@MessagingGateway
public interface DownloadGateway1 {
@Gateway(requestChannel = "sftpChannel1")
List<File> start(String dir);
}
@Bean(name="sftpChannel1")
public MessageChannel sftpChannel1() {
return new DirectChannel();
}

没错,服务器是在会话工厂中指定的,而不是在网关中指定的。该框架确实提供了一个委派会话工厂,允许为发送到网关的每个消息从一个已配置的工厂中进行选择。请参阅委派会话工厂。

编辑

这里有一个例子:

@SpringBootApplication
public class So46721822Application {
public static void main(String[] args) {
SpringApplication.run(So46721822Application.class, args);
}
@Value("${sftp.name}")
private String[] names;
@Value("${sftp.host}")
private String[] hosts;
@Value("${sftp.user}")
private String[] users;
@Value("${sftp.pwd}")
private String[] pwds;
@Autowired
private DelegatingSessionFactory<?> sessionFactory;
@Autowired
private SftpGateway gateway;
@Bean
public ApplicationRunner runner() {
return args -> {
try {
this.sessionFactory.setThreadKey("one"); // use factory "one"
this.gateway.send(new File("/tmp/f.txt"));
}
finally {
this.sessionFactory.clearThreadKey();
}
};
}
@Bean
public DelegatingSessionFactory<LsEntry> sessionFactory() {
Map<Object, SessionFactory<LsEntry>> factories = new LinkedHashMap<>();
for (int i = 0; i < this.names.length; i++) {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory();
factory.setHost(this.hosts[i]);
factory.setUser(this.users[i]);
factory.setPassword(this.pwds[i]);
factories.put(this.names[i], factory);
}
// use the first SF as the default
return new DelegatingSessionFactory<LsEntry>(factories, factories.values().iterator().next());
}
@ServiceActivator(inputChannel = "toSftp")
@Bean
public SftpMessageHandler handler() {
SftpMessageHandler handler = new SftpMessageHandler(sessionFactory());
handler.setRemoteDirectoryExpression(new LiteralExpression("foo"));
return handler;
}
@MessagingGateway(defaultRequestChannel = "toSftp")
public interface SftpGateway {
void send(File file);
}
}

具有属性。。。

sftp.name=one,two
sftp.host=host1,host2
sftp.user=user1,user2
sftp.pwd=pwd1,pwd2

最新更新