简体   繁体   English

在Linux中将Java进程作为服务运行

[英]Running Java process as Service in Linux

I need to run a Java process as a service in (Red Hat 6.4) Linux (It needs to run at boot time and stay up). 我需要在(Red Hat 6.4)Linux中运行Java进程作为服务(它需要在启动时运行并保持运行)。 I have it mostly working, except for it doesn't seem to status correctly in the "Service Configuration" window. 我主要使用它,除了它在“服务配置”窗口中似乎没有正确的状态。

To illustrate, I made a simple Java program: 为了说明,我做了一个简单的Java程序:

package service;

public class JavaService {

    public static void main(String args[]){

        System.out.println("Starting Java-Service");
        while(true){

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("Java-Service is still running..");
        }
    }
}

I jarred that up, and put it at this location: /opt/service/lib 我震惊了,把它放在这个位置:/ opt / service / lib

Then, I created this script: /opt/service/bin/run_java_service 然后,我创建了这个脚本:/ opt / service / bin / run_java_service

#!/bin/tcsh
#
# chkconfig: 2345 80 30
# description: java-service Service

setenv JAVA_SERVICE_HOME /opt/service
setenv CLASSPATH $JAVA_SERVICE_HOME/lib/JavaService.jar

setenv SERVICE_PID  `ps aux | grep JavaService | grep -v grep | awk '{print $2}'`;

if ( (stop == $1  || restart == $1)) then
    echo "java-service stop";
    kill -9 $SERVICE_PID
    setenv SERVICE_PID
endif

if ( start == $1 || restart == $1 ) then
    if($SERVICE_PID) then
        echo "java-service is already running"
    else
        echo "java-service start";
        java service.JavaService&
    endif
endif

if (status == $1) then
    if($SERVICE_PID) then
        echo "java-service (pid $SERVICE_PID) is running...";
    else
        echo "java-service is stopped";
    endif
endif

I then created a symlink to this in the /etc/rc.d/init.d directory and added it to the chkconfig: 然后我在/etc/rc.d/init.d目录中创建了一个符号链接,并将其添加到chkconfig:

sudo ln –s /opt/service/bin/run_java_service /etc/rc.d/init.d/java-service
sudo chkconfig --add java-service

At this point, commands like this work as expected from the command line: 此时,这样的命令可以从命令行按预期工作:

sudo service java-service stop
sudo service java-service start
sudo service java-service status

The problem is that things aren't statusing correctly in the "Service Configuration" dialog. 问题是“服务配置”对话框中的状态不正确。 For instance, in this screenshot, I have clicked the "Stop Button" and it still shows as "plugged in". 例如,在此屏幕截图中,我点击了“停止按钮”,它仍显示为“已插入”。

在此输入图像描述

What piece of the puzzle am I missing? 我错过了哪一块拼图?

You could try using jsvc from apache. 您可以尝试使用apache中的jsvc Tomcat use it to be launched as a service. Tomcat使用它作为服务启动。

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

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