通常,一个Java的后台应用程序,在Linux的终端可以启动多个,这样造成资源浪费,甚至相互操作竞争资源导致问题。这里通过也shell脚本启动应用,在shell脚本中做了些限制。就可以巧妙避免重复启动的问题了。
比如应用的目录结构为:
app
bin(存放启动脚本startup.sh和class文件、配置文件等。)
lib(存放引用的库)
假设应用的类名为:mypack.MyAppMain
startup.sh
#!/bin/sh
programdir= "."
program= "mypack.MyAppMain"
num=$#
temp=$CLASSPATH
#setting libs path
libs=../lib/*
append(){
temp=$temp ":"$1
}
for file in $libs; do
append $file
done
export CLASSPATH=$temp:.:../:$programdir
export LANG=zh_CN
res=`ps aux|grep java|grep $program|grep -v grep|awk '{print $2}'`
if [ -n "$res" ]
then
echo "MyAppMain already running"
else
nohup java -classpath $CLASSPATH mypack.MyAppMain &
sleep 3
unset res
res=`ps aux|grep java|grep $program|grep -v grep|awk '{print $2}'`
if [ -n "$res" ]
then
echo "MyAppMain start success"
else
echo "MyAppMain start error"
fi
fi
programdir= "."
program= "mypack.MyAppMain"
num=$#
temp=$CLASSPATH
#setting libs path
libs=../lib/*
append(){
temp=$temp ":"$1
}
for file in $libs; do
append $file
done
export CLASSPATH=$temp:.:../:$programdir
export LANG=zh_CN
res=`ps aux|grep java|grep $program|grep -v grep|awk '{print $2}'`
if [ -n "$res" ]
then
echo "MyAppMain already running"
else
nohup java -classpath $CLASSPATH mypack.MyAppMain &
sleep 3
unset res
res=`ps aux|grep java|grep $program|grep -v grep|awk '{print $2}'`
if [ -n "$res" ]
then
echo "MyAppMain start success"
else
echo "MyAppMain start error"
fi
fi
然后通过此脚本来启动,就可以解决问题了。
注意:
启动时候还可能出现startup.sh没有执行权限的问题,改为777。
还有可能出现错误信息:
: bad interpreter: 没有那个文件或目录
这是因为startup.sh脚本的编码不对,你需要保证文档格式是UNIX的,这个问题好多人栽过跟头,我也不例外,以为shell脚本语法不对,其实是文件编码的问题!
下面给出没有限制的重复启动问题的脚本:
#!/bin/sh
programdir= "."
num=$#
temp=$CLASSPATH
#setting libs path
libs=../lib/*
append(){
temp=$temp ":"$1
}
for file in $libs; do
append $file
done
export CLASSPATH=$temp:.:../:$programdir
export LANG=zh_CN
nohup java -classpath $CLASSPATH mypack.MyAppMain &
programdir= "."
num=$#
temp=$CLASSPATH
#setting libs path
libs=../lib/*
append(){
temp=$temp ":"$1
}
for file in $libs; do
append $file
done
export CLASSPATH=$temp:.:../:$programdir
export LANG=zh_CN
nohup java -classpath $CLASSPATH mypack.MyAppMain &
同样,配合这个启动脚本的还有一个关闭脚本:
#!/bin/sh
proc=MyAppMain
echo "$proc 进程是否存在"
echo `jps |grep $proc`
proc_id=`jps |grep $proc|awk ' {print $1}'`
if [ -n "$proc_id" ]
then
echo " $proc is start,now kill......"
kill -9 $proc_id
echo " $proc kill ok !!!!!!!!!!!!!"
else
echo " $proc is not start!!!!!!!!!!!"
fi
proc=MyAppMain
echo "$proc 进程是否存在"
echo `jps |grep $proc`
proc_id=`jps |grep $proc|awk ' {print $1}'`
if [ -n "$proc_id" ]
then
echo " $proc is start,now kill......"
kill -9 $proc_id
echo " $proc kill ok !!!!!!!!!!!!!"
else
echo " $proc is not start!!!!!!!!!!!"
fi
本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/243360,如需转载请自行联系原作者