且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在servlet容器中启动线程池

更新时间:2023-12-03 13:28:22

这不是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.