1.一个判断服务是否启动的监控类
package com.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RequestUtil {
/**
* 网站是否正常运转
* @return
*/
public static boolean isWebSiteNormal(String urlStr){
try {
if(urlStr != null && urlStr.indexOf("://") <= 0 ){
urlStr = "http://"+urlStr;
}
URL url = new URL(urlStr);
URLConnection con = url.openConnection();
BufferedReader in = new BufferedReader(new java.io.InputStreamReader(con
.getInputStream()));
con.setConnectTimeout(2000);
con.setReadTimeout(6000);
String s = "";
while ((s = in.readLine()) != null) {
if (s.length() > 0) {
return true;
}
}
in.close();
} catch (Exception e) {
LogUtil.writerE(e);
}
return false;
}
/**
* 查看Tomcat7服务是否正在运行
* @return
*/
public static boolean isTomcatServiceAlive(){
try {
Process process = Runtime.getRuntime().exec("lsof -i tcp:80");
InputStreamReader ir = new InputStreamReader(process.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null) {
if(line != null && !"".equals(line)){
return true;
}
}
} catch (java.io.IOException e) {
LogUtil.writerE(e);
}
return false;
}
/**
* 获取tomcat监听的进程
* @return
*/
public static String getTomcatTcpIpListener(){
StringBuffer str = new StringBuffer();
try {
Process process = Runtime.getRuntime().exec("lsof -i tcp:80");
InputStreamReader ir = new InputStreamReader(process.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null) {
if(line != null && !"".equals(line)){
str.append(line).append("\n");
}
}
} catch (java.io.IOException e) {
LogUtil.writerE(e);
}
return str.toString();
}
/**
* 获取tomcat监听的进程
* @param content
* @return
*/
public static Set<Integer> getUids(String content){
Pattern pattern = Pattern.compile("java\\s*[0-9]*");
Matcher matcher = pattern.matcher(content);
Pattern pattern2 = Pattern.compile("[0-9]+");
Set<Integer> uidSet = new HashSet<Integer>();
while(matcher.find()){
Matcher matcher2 = pattern2.matcher(matcher.group());
if(matcher2.find()){
if(matcher2.group() != null && !"".equals(matcher2.group())){
uidSet.add(Integer.parseInt(matcher2.group()));
}
}
}
return uidSet;
}
public static boolean isWebCanVisite(String url) {
if(url != null && url.lastIndexOf("://") <= 0 ){
url = "http://"+url;
}
LogUtil.writerINF("Check Url:"+url);
String content = HttpRequestProxy.doGet(url,"utf-8");
// Pattern pattern = Pattern.compile("<title>\\s*[^<>][^<>]*\\s*</title>");
// Pattern pattern2 = Pattern.compile("[^x00-xff]*");
if(content != null){
return true;
// Matcher matcher = pattern.matcher(content);
// String temp = "";
// while(matcher.find()){
// temp = matcher.group();
// temp = temp.trim();
// if(temp.length() > 16){
// temp = temp.substring(7, temp.length()-8);
// Matcher matcher2=pattern2.matcher(temp);
// if(matcher2.find()){
// return true;
// }
// }
// }
}
return false;
}
}
2.一个Tomcat服务控制工具类
package com.util;import java.util.Iterator;
import java.util.Set;
public class TomcatUtil {
/**
* 关闭tomcat7服务
* @return
*/
public static boolean stopTomcat() {
try {
String commandstr = "/usr/local/tomcat7/bin/shutdown.sh";
Process p;
LogUtil.writerINF("Tomcat7 ShutDown");
p = Runtime.getRuntime().exec(commandstr);
if (p.waitFor() == 0){
LogUtil.writerINF("Tomcat7 ShutDown over");
return true;
}else{
LogUtil.writerINF("Tomcat7 ShutDown fail");
return false;
}
} catch (Exception e) {
LogUtil.writerINF("Tomcat7 ShutDown fail");
LogUtil.writerE(e);
return false;
}
}
/**
* 开启服务
* @return
*/
public static boolean startTomcat() {
try {
String commandstr = "/usr/local/tomcat7/bin/startup.sh";
Process p;
LogUtil.writerINF("Tomcat7 startup");
p = Runtime.getRuntime().exec(commandstr);
if (p.waitFor() == 0){
LogUtil.writerINF("Tomcat7 startup over");
return true;
}else{
LogUtil.writerINF("Tomcat7 startup fail");
return false;
}
} catch (Exception e) {
LogUtil.writerINF("Tomcat7 startup fail");
LogUtil.writerE(e);
return false;
}
}
/**
* 杀掉进程
* @param uidSet
* @return
*/
public static int killUid(Set<Integer> uidSet){
Iterator<Integer> it = uidSet.iterator();
int successCount = 0 ;
while(it.hasNext()){
int uid = it.next();
try {
String commondStr = "kill -9 "+uid;
Process p = Runtime.getRuntime().exec(commondStr);
if (p.waitFor() == 0){
LogUtil.writerINF("java "+uid+" be Killed");
successCount ++;
}else{
LogUtil.writerINF("java "+uid+" be Kill Failed");
}
} catch (Exception e) {
LogUtil.writerE(e);
}
}
return successCount;
}
}
3.Email发送工具类
package com.util;import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.MimeMessage.RecipientType;
/**
* MailUtil
* @author Administrator
*
*/
public class MailUtils {
private String MAIL_NAME = "****";
private String MAIL_PASSWORD = "******";
private String mailHost = "smtp.163.com";
private String MAIL_FROM = "******@163.com";
private String MAIL_FROM_NAME = "****";
public MailUtils(){
}
public MailUtils(String username,String password,String mailHost,String mailFrom,String mailFromName ){
this.MAIL_NAME = username;
this.MAIL_PASSWORD = password;
this.mailHost = mailHost;
this.MAIL_FROM = mailFrom;
this.MAIL_FROM_NAME = mailFromName;
}
/**
* 邮箱认证
* @param userAuth
* @param mailType
* @return
* @throws Exception
*/
public Session mailAuth() throws Exception{
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "true");
props.setProperty("mail.host", mailHost);
Session session = Session.getDefaultInstance(props,new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MAIL_NAME,MAIL_PASSWORD);
}
});
return session;
}
/**
* @param subject
* @param content
* @param mailTo
* @throws Exception
*/
public void sendSimpleMail(String subject,String content,String mailTo) throws Exception{
Session session = mailAuth();
session.setDebug(true);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(MimeUtility.encodeText(MAIL_FROM_NAME)+"<"+MAIL_FROM+">" ));
msg.setSubject(subject);
msg.setText(content);
msg.addRecipient( RecipientType.TO, new InternetAddress(mailTo));
Transport.send(msg);
}
public void sendMutilHtmlMail(String subject,String content,List<String> mailto) throws Exception{
if(mailto != null){
for(int i = 0 ; i < mailto.size() ; i++){
sendHtmlMail(subject, content,mailto.get(i));
}
}
}
}
4.生成日志工具类
package com.util;import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LogUtil {
private static String FILE_PATH = "/usr/local/tomcatLook/";
public static void writerINF(String info){
File file = null;
File filedir = null;
BufferedWriter writer = null;
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd_HH:mm:ss");
try {
filedir = new File(FILE_PATH);
if(!filedir.exists()){
filedir.mkdirs();
}
file = new File(FILE_PATH+"domain."+sdf.format(date)+".log");
if(file.exists()){
file.createNewFile();
}
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
writer.write("["+sdf2.format(date)+"]-[INFO]:"+info+"\n");
writer.flush();
} catch (IOException e) {
} finally{
if(writer != null){
try {
writer.close();
} catch (IOException e) {
}
}
writer = null;
file = null;
filedir = null;
date = null;
sdf = null;
sdf2 = null;
}
}
public static void writerE(Exception e){
StringBuffer info = new StringBuffer();
File file = null;
File filedir = null;
BufferedWriter writer = null;
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd_HH:mm:ss");
try {
info.append("[").append(sdf2.format(date)).append("]-[Exception]:").append(e.getClass().getName()).append("\n\t").append(getExceptionString(e)).append("\n");
filedir = new File(FILE_PATH);
if(!filedir.exists()){
filedir.mkdirs();
}
file = new File(FILE_PATH+"domain."+sdf.format(date)+".log");
if(file.exists()){
file.createNewFile();
}
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
writer.write(info.toString());
writer.flush();
} catch (IOException ioe) {
} finally{
if(writer != null){
try {
writer.close();
} catch (IOException ioe2) {
}
}
writer = null;
file = null;
filedir = null;
date = null;
sdf = null;
}
}
/**
* 返回处理后的异常信息
* @param e 异常对象
* @return 处理后的异常信息
*/
private static String getExceptionString(Exception e) {
String errorString = e.toString() + "\r\n";
StackTraceElement[] stackArr = e.getStackTrace();
for (int i = 0; i < stackArr.length; i++) {
errorString += "\tSTACK-->: " + stackArr[i].toString();
if((i+1) != stackArr.length) errorString += "\r\n";
}
return errorString;
}
}
5.入口程序
public class MainProc {private static boolean IS_AUTO = false; //是否自动重启服务
/**
* @param args
*/
public static void main(String[] args) {
MailUtils mail = new MailUtils();
List<String> emails = new ArrayList<String>();
String CheckUrl = "www.*****.com";
emails.add("*****@qq.com");
try {
LogUtil.writerINF("check...");
boolean isRun = RequestUtil.isWebSiteNormal(CheckUrl);
LogUtil.writerINF("First Check status :"+isRun);
int checkCount = 0 ;
while(!isRun&&checkCount<=3){
checkCount ++;
LogUtil.writerINF("check "+checkCount+"time ...");
isRun = RequestUtil.isWebSiteNormal(CheckUrl);
}
if(!isRun){//判断web是否可以访问
LogUtil.writerINF("WebSite Connection Fail... Begin send Email...");
if(IS_AUTO){
mail.sendMutilHtmlMail("网站无法访问!", "网站无法访问,正在重新启动tomcat服务,请稍后检查网站是否可以访问", emails);
LogUtil.writerINF("Email Send Over. Begin Restart Tomcat");
boolean isTomcatRun = RequestUtil.isTomcatServiceAlive();
LogUtil.writerINF("检查Tomcat是否正在运行-IsTomcatRun:"+isTomcatRun);
if(isTomcatRun){//检查出有程序监听80端口
TomcatUtil.stopTomcat();//停止tomcat服务
String tcpContent = RequestUtil.getTomcatTcpIpListener();
if(tcpContent != null && !"".equals(tcpContent)){
Set<Integer> uidSet = RequestUtil.getUids(tcpContent);//获取tomcat的监听的uid
if(uidSet.size() > 0 ){//是否有tomcat程序仍然在监听
TomcatUtil.killUid(uidSet);
}
}
}
TomcatUtil.startTomcat();
Thread.sleep(10*1000);//暂停10秒等待服务完全启动
LogUtil.writerINF("Aleardy Restart Tomcat");
boolean isStartSuccess = RequestUtil.isWebSiteNormal("www.qcwp.com");//判断是否启动成功
int startCheckCount = 0 ;
while(!isStartSuccess&&startCheckCount<=3){
startCheckCount ++;
LogUtil.writerINF("Start Check "+startCheckCount+"time ...");
isStartSuccess = RequestUtil.isWebSiteNormal("www.qcwp.com");
}
if(isStartSuccess){
LogUtil.writerINF("Tomcat Start Success");
mail.sendMutilHtmlMail("网站重启启动成功!", "网站重启成功,现在可以正常访问!", emails);
}else{
LogUtil.writerINF("Tomcat Start Fail");
mail.sendMutilHtmlMail("网站重启启动失败!", "网站重启失败,请手动重启服务!", emails);
}
}else{
mail.sendMutilHtmlMail("网站无法访问!", "网站无法访问,请手动重新启动tomcat服务", emails);
}
}
} catch (Exception e) {
LogUtil.writerE(e);
}
}
}
代码全部都贴出来了。。其中有email发送的工具类,记得加mail.jar包
另外打包的时候不能直接用MyEclipse打包。需要用Fat-jar 插件才能把导入的jar包与代码一起导出来