微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JSch - Vertx.Future - 使用相同会话和 ChannelSftp 的并行进程

如何解决JSch - Vertx.Future - 使用相同会话和 ChannelSftp 的并行进程

我有一个项目需要使用异步编程(Promise-Future),并且需要使用 JSch 打开 do process Move、Remove 和 Upload files。

这是示例代码(我对我的项目进行了类似的行为)

class Main {
  public static void main(String[] args) {
    List<Future> futureList = new ArrayList<>();
    for(int i = 0 ; i < 100 ; i++){
      //Processing object,and complete Future
      Promise<String> promise = Promise.promise();
      //this is for sample test,it actually calling api service that took a long time 
      //to process and return the object,that's why I am using Future
      processFuture(promise.future());
    }
  }

  private static void processFuture(Future future){
    future.all(futureList).onComplete(res ->{
      if(res.succeeded()){
         Session session = null;
         ChannelSftp channelSftp = null;
        try{
          Session session = connectSession();
          Channel channel = session.openChannel("sftp");
          channelSftp = (ChannelSftp) channel;
          channelSftp.connect(2000);

          for(int j = 0 ; j < res.result().list().size(); j++){
            if(channelSftp.isConnected()){
                //Process Data with SFTP here
            }
          }
          channelSftp.disconnected();
          session.disconnected();
        }catch(Exception e){
          channelSftp.disconnected();
          session.disconnected();
        }
      }
    });
  }

  private static void connectSession(){
    JSch jsch = new JSch();
    Session session = null;
    try{
        session = jsch.getSession(userSetting,hostSetting,portSetting);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking","no");
        session.setConfig(config);
        session.setPassword(passwordSetting);
        session.connect();

    }catch(Exception e){
      throw e;
    }
    return session;
  }
}

这里的问题是,当运行 processFuture 处理数据到 sftp 时,它会一直打开同一个会话,它会给出很多错误,比如会话超时,或错误读取 sftp 文件等>

解决方法

根据@Martin 的参考资料和信息,我决定更改我的算法代码并使其在使用 sftp 处理数据之前等待异步进程的结果。

原因是因为 SFTP 无法以 100% 相同的配置打开多个相同的会话。比以前慢了一点,因为我需要等待服务先处理,但它现在成功处理了我的数据。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。