有时部署项目时使用多个应用服务器做负载均衡,这里使用多个Tomcat做负载。
服务器环境: CentOS 6.5
Tomcat目录: /usr/local
Tomcat目录下有tomcat1、tomcat2、tomcat3、tomcat4 四个tomcat实例。
tomcat实例的命名规则: tomcat${i}
1. 新建一个shell文件命名为 tomcat.sh
#!/bin/bash # Apache Tomcat daemon # # chkconfig: 345 10 10 # description: Apache Tomcat daemon # # processname: tomcat export JAVA_HOME=/usr/local/java/jdk1.7.0_80 #define variables tom="/usr/local/tomcat" startup_bin="bin/startup.sh" shutdown_bin="bin/shutdown.sh" usage="{p2|p3|all} {start|stop|restart|status}" dev="/dev/null" #judge $1 $2 whether null if [ "$1" == "" -o "$2" == "" ];then echo echo "Usage: $0 $usage" echo exit 1 fi #judge $1 case $1 in "p3") tomcats="1 2 3" ;; "p2") tomcats="1 2" ;; "all") tomcats="1 2 3 4" ;; *) echo "Usage: $0 $usage" ;; esac #define start function tomcatstart() { for i in $tomcats do tom_home="$tom$i" run_status=$(ps -ef | grep -v 'grep' | egrep "java.*=${tom_home}") if [ "${run_status}X" != "X" ];then echo "tomcat$i is already running..." else ${tom_home}/${startup_bin} &>$dev echo "tomcat$i starting,Please wait 2s..." sleep 2 fi done } #define stop function tomcatstop() { for j in $tomcats do tom1_home="$tom$j" run1_status=$(ps -ef | grep -v 'grep' | egrep "java.*=${tom1_home}") if [ "${run1_status}X" == "X" ];then echo "tomcat$j is not running..." else ${tom1_home}/${shutdown_bin} &>$dev echo "tomcat$j stopping,Please wait 2s..." sleep 2 fi done } #define restart function tomcatrestart() { for m in $tomcats do tom2_home="$tom$m" run2_status=$(ps -ef | grep -v 'grep' | egrep "java.*=${tom2_home}") if [ "${run2_status}X" == "X" ];then echo "tomcat$m is not running..." ${tom2_home}/${startup_bin} &>$dev echo "tomcat$m starting,Please wait 2s..." sleep 2 else ${tom2_home}/${shutdown_bin} &>$dev echo "tomcat$m stopping,Please wait 2s..." sleep 2 ${tom2_home}/${startup_bin} &>$dev echo "tomcat$m starting,Please wait 2s..." sleep 2 fi done } #define status function tomcatstatus() { for n in $tomcats do tom3_home="$tom$n" run3_status=$(ps -ef | grep -v 'grep' | egrep "java.*=${tom3_home}") if [ "${run3_status}X" == "X" ];then echo "tomcat$n is not running..." else echo "tomcat$n is running" fi done } #judge $2 case $2 in "start") tomcatstart ;; "stop") tomcatstop ;; "restart") tomcatrestart ;; "status") tomcatstatus ;; *) echo "Usage: $0 $usage" ;; esac
2. 修改文件tomcat.sh的权限,更改为可执行
chmod +x tomcat.sh
3. 启动tomcat命令
比如想启动tomcat1和tomcat2两个实例:
./tomcat.sh p2 start
停止命令:
./tomcat.sh p2 stop
4. 把tomcat脚本配置为系统服务
cp tomcat.sh /etc/init.d/tomcat
sudo chkconfig --add /etc/init.d/tomcat
查看是否已添加进服务列表
chkconfig --list
添加到服务以后, 就可以这样以服务方式来启动和停止、重启tomcat了。
service tomcat p2 start