简体   繁体   English

在Java Servlet中创建异步处理

[英]Creating an asynchronous processo in a java servlet

I want to create a java servlet that runs an .exe application in the server but as an asynchronous process and returns to the client a hash or token to indentify the process so the client can ask later if the process has finished. 我想创建一个Java Servlet,该Java Servlet在服务器中运行.exe应用程序,但作为异步进程,并向客户端返回哈希或令牌以标识该进程,以便客户端稍后可以询问进程是否已完成。

For example: 例如:

I know that I can use ProcessBuilder or Runtime.exec() to run the .exe application, but I don't know how to make the servlet leave the process running and responds. 我知道我可以使用ProcessBuilder或Runtime.exec()来运行.exe应用程序,但是我不知道如何使servlet保持进程运行并响应。

Thanks! 谢谢!

Regards, 问候,

Xtian tian田

The Process returned by ProcessBuilder is run asynchronously in the background (it's a separate process), so as soon as you call .start() you can have the servlet respond. ProcessBuilder返回的Process在后台异步运行(这是一个单独的进程),因此,只要调用.start() ,就可以让Servlet响应。

If you're seeing the subprocess never finish that would be because you're not reading its output , which you must do in order for the process to continue. 如果您看到子流程永远不会完成,那是因为您没有在读取其输出 ,必须执行该操作才能使该流程继续。 You may want to do this in a separate background thread. 您可能需要在单独的后台线程中执行此操作。

This is one of the ways to implement this: 这是实现此目的的方法之一:

  1. Create a runnable that executes the command (Runtime.exec etc) (a few other things will follow) 创建一个执行命令(Runtime.exec等)的可运行对象(随后将执行其他一些操作)
  2. Create an id lets say a UUID and initialize the status against the id on a persistant storage to say PENDING 创建一个ID可以说一个UUID并根据持久性存储上的ID初始化状态来说PENDING
  3. Use a ThreadPoolExecutor, add the runnable to the workQueue allocated to the threadpool. 使用ThreadPoolExecutor,将可运行对象添加到分配给线程池的workQueue中。
  4. When the runnable starts executing, it may change the status in say DB to IN_PROGRESS 当可运行程序开始执行时,它可能会将状态数据库中的状态更改为IN_PROGRESS
  5. When the task is completed you can mark the status as COMPLETE 任务完成后,您可以将状态标记为“完成”

Now at any point of time for the request coming in you shall be able to check the status of the task and respond back accordingly. 现在,在任何时候收到请求时,您都可以检查任务的状态并做出相应的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM