问题描述
我是java领域的新手,也是tomcat领域的新手.因此,问题是:
I'm new on the java universe, also new in the tomcat world. So, the issue is:
我需要将Java类作为守护程序运行.此类应能够与tomcat请求进行通讯.
I need to run a java class as a daemon. This class should be able to comunicate with the tomcat requests.
过去:当我在C语言中执行此操作时,我将二进制文件作为后台进程执行.
In the past: when I did this in C, I executed the binary file as a background process.
您能给我一些建议如何进行吗?
Could you give me some suggestions how to proceed?
提前感谢!!
推荐答案
因此,答案似乎有两部分.第一个是确保您的守护进程已使用tomcat容器启动,第二个是确保正确配置了您的线程,以便在关机后不让该tomcat实例保持活动状态.
So it sounds like there are two parts to the answer. The first one is to make sure that your daemon gets started up with the tomcat container, and the other is to ensure that your thread gets properly configured so as not to keep the tomcat instance alive after shutdown.
由于有关线程的部分比较简单,因此我将首先解决它.产生的所有线程都应该是守护程序线程(例如,您已调用 Thread.setDaemon(true)).引用自 O'reilly的Java探索线程章节:
Since the part about threading is simpler, I'll get that out of the way first. All the threads that you spawn should be daemon threads (e.g. you've called Thread.setDaemon(true)). Quoting from O'reilly's Exploring Java's Chapter on Threads :
具有活动的非守护程序线程将阻止Tomcat的干净关闭.原因是tomcat会保持一个非守护进程线程运行,直到它收到关闭消息为止,此时该线程已停止.如果还有其他非守护进程线程,那么JVM将愉快地保持轻击,并且您必须从命令行中终止该进程.
Having live non-daemon threads will prevent the clean shutdown of tomcat. The reason for this is that tomcat keeps one non-daemon thread running up until it receives the shutdown message, at which point, said thread is stopped. If there are other non-daemon threads, then the JVM will happily keep puttering along, and you'll have to kill the process from the command line.
现在我们进入servlet容器的生命周期,以产生我们的服务.这里有两个步骤...我们必须按照Jim Garrison的建议实现ServletContextListener
,然后我们必须告诉容器加载它.这里有两件事:
And now we get on to hooking into the lifecycle of the servlet container in order to spawn our service. There are two steps here...we have to implement a ServletContextListener
as Jim Garrison suggested, and then we have to tell the container to load it. There are two things here:
第1步:实施ServletContextListener
:
public class MyDaemonServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
Thread th = new Thread() {
public void run() {
// implement daemon logic here.
}
};
th.setDaemon(true);
th.start();
}
public void contextDestroyed(ServletContextEvent sce) {
// you could notify your thread you're shutting down if
// you need it to clean up after itself
}
}
第2步:在您的web.xml
中声明它:
Step 2 : Declare it in your web.xml
:
<listener>
<listener-class>MyDaemonServletContextListener</listener-class>
</listener>
那应该就是那个.
这篇关于如何使用tomcat将类设置为守护程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!