【问题标题】:How to run multiple long task method in the same time in Spring Boot Service?如何在 Spring Boot Service 中同时运行多个长任务方法?
【发布时间】:2021-03-26 11:06:49
【问题描述】:

这是我的问题,我创建了一个服务类,用于处理将文件从输出文件夹上传到云端。在这个输出文件夹内,触发时会产生大量文件。

以下是我的服务等级。

     @Service
     Public class uploadService {
         
         public void UploadAllFile(String processCode) {

             if (processCode = "allfile") {

          1      //no need check generate status, start to upload while files generating
                 //keep upload files while generate process ongoing, until finish generate.
                 uploadPDF();

                  
          2      //check other type of files generate status, wait all finish just start upload.
                 ReadFileGenerateLog;
                 if (log.contain("txt") == "all finish generate") {
                       uploadTxt();
                 }
                 if (log.contain("xml") == "all finish generate") {
                       uploadXml();
                 }
             }
         }


         public void UploadPDF(){

         }

         public void UploadTxt(){

         }

         public void UploadXml(){

         }
     }

现在的问题是需要生成和上传几百个 PDF 文件,整个过程需要 1 小时 smtg 完成(上传时仍然生成直到完成)。而其他类型的文件则需要 10 分钟完成(等到完成生成和上传)。

所以根据我的代码逻辑,不可能等待 [1] 函数完成然后才启动 [2] 函数。无论如何,我可以同时运行两个逻辑而不是等待第一个逻辑完成吗?请教我解决这个问题。

【问题讨论】:

标签: java spring spring-boot asynchronous


【解决方案1】:
ExecutorService executor = Executors.newFixedThreadPool(10);

for(int i = 0; i < FILE_COUNT; i++) {
   executor.submit(() -> {
      uploadPDF(i)
   })
}

只需使用 ExecutorService 即可管理多线程上传 PDF。你也可以得到结果如果你调查https://www.baeldung.com/java-executor-service-tutorial

【讨论】:

  • 好的,工作!!抱歉这么晚才回复。谢谢你的建议!!!!
猜你喜欢
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多