通过java代码启动tomcat
解决方法:
1.核心代码
public String runTomact(String cmd){
String start = "success";
BufferedReader in = null;
try {
Process p = Runtime.getRuntime().exec(cmd);
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
String t = "重启完成";
while ((s = in.readLine()) != null) {
if (s.indexOf(t) != -1) {
start = "success";
}
}
} catch (Exception e) {
}finally{
if(in!=null)
try {
in.close();
} catch (IOException e) {
}
}
return start;
}
2.使用方法:
加入tomcat的名字为tomcat_my,startup_tomcat.sh中的内容修改自己tomcat的路径即可
runTomact("/usr/local/java/tomact/tomcat7/bin/startup_tomcat.sh");
3.startup_tomcat.sh
#!/bin/sh
# 获取tomcat进程ID
TomcatID=$(ps -ef |grep tomcat |grep -w 'tomact/tomcat_my/conf'|grep -v 'grep'|awk '{print $2}')
# tomcat启动程序(这里注意tomcat实际安装的路径)
StartTomcat=/usr/local/java/tomact/tomcat_my/bin/startup.sh
TomcatCache=/usr/local/java/tomact/tomcat_my/work
TomcatMonitorLog=/usr/local/java/tomact/tomcat_my/TomcatMonitor.log
Monitor()
{
echo "[$(date +'%F %H:%M:%S')]--[info]--监控到Tomcat异常..."
if [[ $TomcatID ]];then # 这里判断TOMCAT进程是否存在
echo "[$(date +'%F %H:%M:%S')]--[info]--进程存在!先Kill进程,然后重启Tomcat"
kill -9 $TomcatID # 杀掉原tomcat进程
sleep 3
rm -rf $TomcatCache # 清理tomcat缓存
$StartTomcat # 重启Tomact
echo "[$(date +'%F %H:%M:%S')]--[info]--重启完成!"
else
echo "[$(date +'%F %H:%M:%S')]--[info]--tomcat进程不存在!直接重启..."
rm -rf $TomcatCache # 清除缓存
$StartTomcat # 重启Tomact
echo "[$(date +'%F %H:%M:%S')]--[info]--重启完成!"
fi
echo "-------------------------------------------------------------------------------------------------"
}
Monitor>>$TomcatMonitorLog
本文链接:http://www.yayihouse.com/yayishuwu/chapter/1760