Servlet 中的线程
我正在开发一个 servlet,可能需要几个小时才能完成请求。然而,调用 servlet 的客户端只关心知道 servlet 是否已接收到请求。客户端不想等待几个小时才能从 servlet 获得任何类型的响应。此外,由于调用 servlet 是阻塞调用,因此客户端在收到 servlet 的响应之前无法继续操作。 为了避免这种情况,我正在考虑在 servlet 代码中实际启动一个新线程。 servlet 启动的线程将执行耗时的处理,从而使 servlet 能够非常快速地将响应返回给客户端。但我不确定这是否是一种可以接受的解决 servlet 调用阻塞性质的方法。我研究过 NIO,但似乎并不能保证它可以在任何 servlet 容器中工作,因为 servlet 容器也是基于 NIO 的。
I am working on a servlet that can take a few hours to complete the request. However, the client calling the servlet is only interested in knowing whether the request has been received by the servlet or not. The client doesn't want to wait hours before it gets any kind of response from the servlet. Also since calling the servlet is a blocking call, the client cannot proceed until it receives the response from the servlet.
To avoid this, I am thinking of actually launching a new thread in the servlet code. The thread launched by the servlet will do the time consuming processing allowing the servlet to return a response to the client very quickly. But I am not sure if this an acceptable way of working around the blocking nature of servlet calls. I have looked into NIO but it seems like it is not something that is guaranteed to work in any servlet container as the servlet container has be NIO based also.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
线程还不错,但我建议将其作为任务扔到执行器池中。更好的是一个长期运行的工作经理。按照计划快速返回并不是一个坏习惯。我建议提供某种用户反馈,指示用户可以在哪里找到有关长时间运行的作业的信息。因此:
包含结果的页面必须与此后台作业管理器协调。在计算时,您可以让此页面描述进度。完成后,页面可以显示长时间运行作业的结果。
A thread isn't bad but I recommend throwing this off to an executor pool as a task. Better yet a long running work manager. It's not a bad practice to return quickly like you plan. I would recommend providing some sort of user feedback indicating where the user can find information about the long running job. So:
The page with the result will have to coordinate with this background job manager. While it's computing you can have this page describe the progress. When its done the page can display the results of the long running job.
您需要的是作业调度程序,因为它们可以保证作业将完成,即使服务器重新启动也是如此。
查看 java OSS 作业调度程序,最值得注意的是 Quartz。
What you need is a job scheduler because they give assurance that a job will be finished, even in case a server is restarted.
Take a look at java OSS job schedulers, most notably Quartz.
您的解决方案是正确的,但在企业应用程序中创建线程被认为是一种不好的做法。最好使用 线程池 或 JMS队列。
你必须考虑到服务器在处理过程中宕机会发生什么,当多个请求(想想:数百甚至数千)同时发生时如何反应等等。所以你选择了正确的方向,但它有点更复杂。
Your solution is correct, but creating threads in enterprise applications is considered a bad practice. Better use a thread pool or JMS queue.
You have to take into account what should happen server goes down during processing, how to react when multiple requests (think: hundreds or even thousands) occur at the same time, etc. So you have chosen the right direction, but it is a bit more complicated.