如何从 Spring 中的组件调用配置中的 SFTP 出站网关操作

How to call SFTP Outbound Gateway operations in Configuration from Component in Spring

我看过这里 here,但无法让 listFiles 工作:

    @Bean
    public SessionFactory<LsEntry> sftpSessionFactory() {
        DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
        factory.setHost("localhost");
        factory.setPort(port);
        factory.setUser("foo");
        factory.setPassword("foo");
        factory.setAllowUnknownKeys(true);
        factory.setTestSession(true);
        return new CachingSessionFactory<LsEntry>(factory);
    }

    @MessagingGateway
    public interface MyGateway {
         @Gateway(requestChannel = "sftpChannel")
         List<File> listFiles();

    }
    @Bean
    @ServiceActivator(inputChannel = "sftpChannel")
    public MessageHandler handler() {
        return new SftpOutboundGateway(ftpSessionFactory(), "ls", "'my_remote_dir/'");
    }

在我的@Component class 我有这个:

    @Autowired
    MyGateway gateway;

    public void list(){
        List<File> files = gateway.listFiles();
    }

当我 运行 执行此操作时,出现错误 receive is not supported, because no pollable reply channel has been configured

我认为这是我的 knowledge/understanding 集成渠道的问题。也许我缺少一个 bean,但我的主要目标是替换我当前使用的 inboundchannel 适配器来临时请求文件,而不是连续轮询文件服务器

是的,Spring Integration Gateway with no arguments中提到的故事肯定与您的问题有关。

您忽略了 List<File> listFiles() 合同没有参数的事实,因此框架不清楚要使用什么发送给 sftpChannel。因此它尝试调用 receive。但是由于你的 sftpChannel 不是 PollableChannel,你得到了那个错误。无论如何,这是一个不同的故事,而不是当您尝试使用该网关合同时,您希望通过向 sftpChannel 发送消息来获得回复。

您只需要更明确地说明使用什么作为无参数网关合约的有效载荷。

在文档中查看更多信息:https://docs.spring.io/spring-integration/docs/current/reference/html/messaging-endpoints.html#gateway-calling-no-argument-methods@Payload 是给你的答案。或者您可以在 @Gateway 注释上指定 payloadExpression 或在 @MessagingGateway.

上指定 defaultPayloadExpression

也许为时已晚,但您也可以将无参数网关合约更改为单参数合约,无需额外注释。

@MessagingGateway
public interface MyGateway {
     @Gateway(requestChannel = "sftpChannel")
     List<File> listFiles(String remoteDir);

}

@Bean
@ServiceActivator(inputChannel = "sftpChannel")
public MessageHandler handler() {
    return new SftpOutboundGateway(ftpSessionFactory(), Command.LS, "payload");
}

在您的@Component class 中,您将拥有:

@Autowired
MyGateway gateway;

public void list(){
    List<File> files = gateway.listFiles("'my_remote_dir/'");
}