在servlet容器中启动线程池 [英] Starting a threadpool in a servlet container

查看:141
本文介绍了在servlet容器中启动线程池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Servlet S,它处理来自第三方网站的回调.

I have a servlet S which handles callbacks from a 3rd party site.

回调调用以特定顺序发生.因此,我需要将它们排队.

The callback invocations happen in a specific order. Thus, I need to queue them.

我建议使用内存队列,例如

I propose to use an in-memory queue like

java.util.ConcurrentLinkedQueue

所以逻辑看起来像这样:

So the logic looks like this:

  • Servlet S收到回调&将接收到的项目排入队列Q.
  • 这一次,托管servlet S实例的线程将终止.
  • 使用者线程从Q读取并依次处理每个线程.

据我了解,每个Servlet S实例都在其自己的线程中执行.

As I understand it, each instance of Servlet S is executed in its own Thread.

如何为将要服务队列的整个Web应用程序(战争)创建一个消费者线程?基本上,我需要以下的单例实例:

How do I create a single Consumer Thread for the whole webapp (war) that will service a Queue ? Basically I need singleton instances of:

  1. 线程池
  2. ConcurrentLinkedQueue

推荐答案

这不是servlet容器的用途.如果要使用基于标准的方法,则确实需要功能更完善的J2EE应用程序服务器.否则,您将拥有骇客,但它们可能足以完成您的任务.

This isn't the sort of thing a servlet container is for. You really need a more full-blown J2EE application server if you're going to use a standards-based approach. What you're going to have are hacks otherwise but they might be sufficient for your task.

我可能会尝试创建一个DaemonServlet.这只是一个普通的servlet,没有映射到URL(也许出于监视目的,可能是盲URL除外,尽管此类情况更喜欢使用JMX).加载servlet时将调用init()方法.您可以在其中启动线程.可以说,您可能需要创建两个:一个可以完成工作.另一个确保第一个正在运行,并在调用destroy()后正常终止它.

What I would probably try is creating a DaemonServlet. This is just a normal servlet that is not mapped to a URL (except, perhaps, a blind URL for monitoring purposes, although prefer JMX for this kind of thing). The init() method is called when the servlet is loaded. You could start a thread in that. Arguably you may need to create two: one that does the work. The other makes sure the first one is running and gracefully terminates it once destroy() is called.

或者,如果您使用的是 Spring (而且,让我们面对现实,那是什么鬼斧神工? '不使用Spring?),您可以在应用程序上下文中简单地创建一个具有相同功能的bean,除了Spring生命周期事件(例如InitializingBean上的afterPropertiesSet())之外.

Alternatively, if you're using Spring (and, let's face of it, what kind of whacko doesn't use Spring?), you could simply create a bean in the application context that does much the same thing, except with Spring lifecycle events (eg afterPropertiesSet() on InitializingBean).

实际上,我有一个更好的建议.使用异步消息使用者,它将更加干净和更具可伸缩性,但这是基于基于 JMS 的解决方案的前提只是一个LinkedBlockingQueue(无论如何,JMS可能是一个更好的主意).但是,根据您的约束,您可能没有JMS可供选择.

Actually, I have an even better suggestion. Use asynchronous message consumers, which will be a lot cleaner and more scalable but this is predicated on a JMS-based solution, rather than just a LinkedBlockingQueue (and JMS is probably a better idea anyway). Depending on your constraints, you may not have JMS available as an option however.

这篇关于在servlet容器中启动线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆