系统环境:CentOS 7 X64、JDK1.8
一:安装jsvc
下载 commons-daemon的源码包
http://apache.fayea.com//commons/daemon/source/commons-daemon-1.0.15-src.zip
解压之后 cd src/native/unix/
执行:
export CFLAGS=-m64
export LDFLAGS=-m64
注意:这2句代码只有64位系统才需要
./configure
make
完成之后,就会在当前目录下生成jsvc文件,把它拷贝到一个目录下,这里是 /home/clouder/vs/jsvc 目录
然后,把JSVC_HOME加入到环境变量
vim .bashrc
export JSVC_HOME=/home/clouder/vs/jsvc
二:编写java代码
启动类必须实现Daemon接口,然后重写start(), stop()方法即可
package com.lala;
import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;
public class Application implements Daemon
{
MyServer server = null;
public void init(DaemonContext context) throws DaemonInitException,Exception
{
server = new MyServer();
}
public void start() throws Exception
{
server.start();
}
public void stop() throws Exception
{
server.stop();
}
public void destroy()
{
System.exit(0);
}
}
注意:pom.xml里面需要加入如下依赖:
<dependency>
<groupId>commons-daemon</groupId>
<artifactId>commons-daemon</artifactId>
<version>1.0.15</version>
</dependency>
三:编写shell脚本
server.sh
#!/bin/bash
if [ "$JAVA_HOME" = "" ]; then
echo "Error: JAVA_HOME is not set."
exit 1
fi
if [ "$JSVC_HOME" = "" ]; then
echo "Error: JSVC_HOME is not set."
exit 1
fi
bin=`dirname "$0"`
export MYJETTY_HOME=`cd $bin/../; pwd`
MYJETTY_CONF_DIR=$MYJETTY_HOME/conf
MYJETTY_WORK_DIR=$MYJETTY_HOME/work
CLASSPATH="${MYJETTY_CONF_DIR}"
for f in $MYJETTY_HOME/lib/*.jar; do
CLASSPATH=${CLASSPATH}:$f;
done
LOG_DIR=${MYJETTY_HOME}/logs
CLASS=com.lala.Application
#jsvc所在的目录
DAEMON_HOME=$JSVC_HOME
PID=${MYJETTY_WORK_DIR}/myjetty.pid
case "$1" in
start)
$DAEMON_HOME/jsvc -Djava.io.tmpdir=$MYJETTY_WORK_DIR -wait 5000 -pidfile $PID -outfile LOG_DIR/myjetty.out -errfile '&1' -cp $CLASSPATH $CLASS
exit $?
;;
stop)
$DAEMON_HOME/jsvc -stop -pidfile $PID $CLASS
exit $?
;;
*)
echo "Usage jsvc start,stop"
exit 1;;
esac
最后,使用:
sh server.sh start启动服务
sh server.sh stop关闭服务
编写Linux系统下Daemon程序的方法步骤:http://www.linuxdiyf.com/linux/603.html
Linux下Daemon的实现:http://www.linuxdiyf.com/linux/5280.html
Linux中部署JAVA程序:http://www.linuxdiyf.com/linux/12172.html
Linux下独立执行Java程序:http://www.linuxdiyf.com/linux/7552.html