在分布式环境开发中经常会使用socket,或者使用rmi来对外提供服务,常用的办法是将写一个java代码,然后部署到服务器上,但是问题来了。如何将这个服务成为一个可靠的系统服务,不会应为风吹草动就挂了,那就不好了。
所以想到使用apache commons 下面的daemon框架来充当守护进程。首先需要在系统中安装jsvc工具具体操作方法这里不作详细说明,请查看 http://commons.apache.org/daemon/jsvc.html。
最后jsvc安装成功之后需要有执行 jsvc -help 会显示以下内容:
Python代码
- ./jsvc -help
- Usage: jsvc [-options] class [args…]
- Where options include:
- -help | –help | -?
- show this help page (implies -nodetach)
- -jvm <JVM name>
- use a specific Java Virtual Machine. Available JVMs:
- ‘client’ ‘server’
- -client
- use a client Java Virtual Machine.
- -server
- use a server Java Virtual Machine.
- -cp / -classpath <directories and zip/jar files>
- set search path for service classes and resouces
- -home <directory>
- set the path of your JDK or JRE installation (or set
- the JAVA_HOME environment variable)
- -version
- show the current Java environment version (to check
- correctness of -home and -jvm. Implies -nodetach)
- -showversion
- show the current Java environment version (to check
- correctness of -home and -jvm) and continue execution.
- -nodetach
- don’t detach from parent process and become a daemon
- -debug
另外需要编写一个shell脚本,来控制该系统服务启动或者停止,详细请操作如下脚本:
Python代码
#!/bin/bash
CLASSPATH=./trigger-server/terminator-job-trigger-server-3.1.0-SNAPSHOT.jar
for P in ls -F ./trigger-server/dependency/
do
CLASSPATH=$CLASSPATH:./trigger-server/dependency/$P
done
#echo $CLASSPATH
export JAVA_HOME=/opt/taobao/java
start(){
echo “starting”
/home/baisui/commons-daemon-1.0.10-native-src/unix/jsvc -pidfile ./pidfile.pid -outfile ./logs/trigger_server_out.log -errfile ./logs/trigger_server_err.log -cp $CLASSPATH com.taobao.terminator.trigger.LaunchServer
echo “start successful”
}
stop(){
/home/baisui/commons-daemon-1.0.10-native-src/unix/jsvc -stop -pidfile ./pidfile.pid -cp $CLASSPATH com.taobao.terminator.trigger.LaunchServer
echo “trigger_server stopped”
}
case “$1” in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
usage
;;
esac
这样可以使用一下脚本来控制系统服务的状态了:
sh start.sh start 启动服务
sh start.sh stop 停止服务
sh start.sh restart 重启服务
本文来源于"阿里中间件团队播客",原文发表时间" 2012-09-20 "