⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sitemonitor.java

📁 淘客在线客服管理系统(TaokeOCS V3.2)
💻 JAVA
字号:
package msg;
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
import   java.sql.*;  
import msg.*;
public class SiteMonitor implements Runnable{
	
	private static Vector sites=null;
	private static long monitorInterval = 1 * 60 * 1000;
	private static long lastMonitorTime=0;
 	private static int numberOfThreads=20;
	private static boolean threadsOn = false;
	//private static PrintWriter   log;//日志  
	private static UserManager userManager=null;
 	private static DbConn[] dbs=null;

	private String fileName="siteMonitor.properties"; 
	private String adMsg="";
	private String smsID="";	
	
	FileWriter  logFW=null;
    PrintWriter logPW=null;
 	String   logFileName ="";
	File logFile=null;
	
	public SiteMonitor(){	
	   if(threadsOn==false){	
	   		init(); 
			userManager=new UserManager();
	   		threadsOn=true;
			dbs=new DbConn[numberOfThreads]; //每个线程一个数据库连接object
 	   		for(int i=0;i<numberOfThreads;i++){
	   			Thread th=new Thread(this);
				th.setName(String.valueOf(i));
 				th.start();
	   		}			
	   }		 
	}
  	public void run(){
		Site site=null;
     	while (threadsOn){  				  
			try{		
				checkInterval(); //sychronized
 				site=getFirstSite();
				if(site!=null){	
 					if( isSiteDead(site) ){	
 						if(site.notifyTimes < site.maxNotifyTimes)							
							notifyCustomer(site,false);
						site.state="dead";
					}else{
						if(site.state.equals("dead")){
							site.state="alive";
							notifyCustomer(site,true);
						}
						else
							site.state="alive";
					}
					changeStateInDb(site);	
					site=null;	
				}					
  				Thread.sleep(30); // 
			}catch (InterruptedException e1) {}   
			catch (Exception e) {
				try{log("Error:"+e.getMessage());}catch(Exception ee){}
			} 
		 	
		}
  	}
	synchronized private Site  getFirstSite(){
		 //index++;
		 Site site=null;
		 if(sites!=null && sites.size()>0){
		 	site=(Site)sites.elementAt(0);
		 	sites.removeElementAt(0);
		 }		 	 
		 return site;
	}  
 	private void notifyCustomer(Site site,boolean recovered){
		String domainId=userManager.getUserDomainId(site.adminId);
		int index=domainId.indexOf(",");
		if(index>0)
			domainId=domainId.substring(0,index);
		if(!userManager.hasMoreSmsCredit(domainId))
			log("网站没有足够的手机短信信用点,不能发送手机短信。");
		else{	
			if( !userManager.hasMoreSmsCredit(domainId,1) ){
				log("站点监控消息发送失败,信用点不足:"+site.domain+" 手机:"+site.adminMobile);
				return;
			}	
			String message="";
			if(recovered==true)
				//userManager.sendSms(site.adminId,site.adminMobile,"贵网站"+site.domain+"现已恢复正常。"+adMsg);		
				message="贵网站"+site.domain+"现已恢复正常。"+adMsg;
			else
				//userManager.sendSms(site.adminId,site.adminMobile,"贵网站"+site.domain+"现处于当机状态。"+adMsg);	
				message="贵网站"+site.domain+"现处于当机状态。"+adMsg;	
			try{				 
				String cell="1234";
				String url="http://"+msg.Global.getParameter("cdomain")+"/sendSms.jsp?id="+smsID+"&cell="+
					   cell+"&mobile="+site.adminMobile+"&message=贵网站"+site.domain+"现已恢复正常。"+adMsg;
				HttpURLConnection hc=(HttpURLConnection)(new URL(url).openConnection());    
				hc.connect();
				InputStream is = hc.getInputStream();  
				DataInputStream data = new DataInputStream(new BufferedInputStream(is));	
				String responseCode=null;
				String t=null;	   
				while (data!=null && (t = data.readLine()) != null ) {   
		   			if(t!=null && !t.equals(""))
			  			responseCode=t;   
				} 
			 	try{
					if(responseCode.indexOf("/")>0){
						// 			 
					}
			   
				}catch(Exception e2){}
				data.close();
				is.close();
				hc.disconnect(); //release the http connection	
				log("通知信息已发:"+site.domain+" 手机:"+site.adminMobile);
			}catch(Exception e){
				log("站点监控消息发送失败,网络故障:"+site.domain+" 手机:"+site.adminMobile);
			}
	 	}	 
	}
	private void changeStateInDb(Site site){
		DbConn db=null;
		try{
			/**
			db=dbs[Integer.parseInt( Thread.currentThread().getName() )];
			if(db==null){
				dbs[Integer.parseInt( Thread.currentThread().getName() )]=new DbConn();
				db=dbs[Integer.parseInt( Thread.currentThread().getName() )];
			}
			**/
			//数据库改为直接调用
			db = new DbConn();
			Calendar now= Calendar.getInstance();
			String nowStr=String.valueOf(now.get(Calendar.YEAR))+"-"+String.valueOf(now.get(Calendar.MONTH)+1)+"-"+
						  String.valueOf(now.get(Calendar.DAY_OF_MONTH))+" "+String.valueOf(now.get(Calendar.HOUR_OF_DAY))+":"+
						  String.valueOf(now.get(Calendar.MINUTE))+":"+String.valueOf(now.get(Calendar.SECOND));
			String sql="update siteMonitor set lastCheckTime=\'"+nowStr+"\', state=\'"+site.state+"\'";
			if(site.state.equals("dead") && site.notifyTimes == 0 ) 
 				sql +=",notifyTimes=notifyTimes+1,lastDeadTime=\'"+nowStr+"\'";
			else if(site.state.equals("dead") && site.notifyTimes < site.maxNotifyTimes) 
 				sql +=",notifyTimes=notifyTimes+1";
 			else if(site.state.equals("alive") && site.notifyTimes >= site.maxNotifyTimes)
				sql +=",notifyTimes=\'0\'";
			sql +=" where domain=\'"+site.domain+"\'";
			if(db.getConnection()==null || db.isClosed())			 
					db.setConnection(); 
			db.setSqlQuery(sql);
			db.executeUpdate();
			if(db.getConnection()!=null && !db.isClosed())
				db.closeConnection();			
		}catch(Exception e){
			try{
				if(db!=null && db.getConnection()!=null && !db.isClosed())
					db.closeConnection();			
			}catch(Exception e1){}
			log("向数据库中修改网站:"+site.domain+"失败。");	
		}	
	}
	synchronized private void  checkInterval(){
		if(System.currentTimeMillis() - lastMonitorTime >= monitorInterval && (sites==null || sites.size()==0)){
			log("启动一次监控");
			getSites();			
			lastMonitorTime=System.currentTimeMillis();			
		}	
	}  
	 
	private boolean isSiteDead(Site site){
		if(site.port==80){
			try{
				System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(site.timeOut)); //连接超时
				HttpURLConnection hc=(HttpURLConnection)(new URL("http://"+site.domain).openConnection()); 	         
				int re=hc.getResponseCode(); 
				hc.disconnect(); //release the http connection
				if(re==200)
					return false;
			}catch (IOException e) {return true;}
		}
		else{
			try{
				Socket s=new Socket();
				SocketAddress sockaddr = new InetSocketAddress(site.domain, site.port);
				s.connect(sockaddr, (int)site.timeOut);
				sockaddr=null;
				s.close();
				return false;
			}catch (IOException e) {return true;}		
		}
		return true;
	}
	synchronized private void getSites(){
		Vector v=new Vector();
		DbConn db=new DbConn();
		String sql="select * from siteMonitor where valid=\'true\'";
		try{
			if(db.getConnection()==null || db.isClosed())			 
					db.setConnection(); 
			db.setSqlQuery(sql);
			ResultSet rs=db.getResult();
			while(rs!=null && rs.next())		 
				v.addElement(new Site(rs.getString("siteId"),rs.getString("domain"), rs.getInt("port"),rs.getLong("timeOut"),
									  rs.getInt("notifyTimes"),rs.getInt("maxNotifyTimes"),rs.getString("state"),
									  rs.getString("adminId"), rs.getString("adminMobile")));
			if(db.getConnection()!=null && !db.isClosed())
				db.closeConnection();
		}catch(Exception e){log(e,"读取站点失败。");}	
		sites=v;
		log(String.valueOf(sites.size())+"个站点被读入内存。");
	}
	public static void main(String[] args){
		new SiteMonitor();	
	}
	class Site{
		String id="";
		String domain="";
		long timeOut=3000;
		int notifyTimes=1;
		int maxNotifyTimes=3;
		String state="alive";
		String adminId="";
		String adminMobile="";
		int port=80;
		public Site(String id,String domain,int port,long timeOut,int notifyTimes,int maxNotifyTimes,String state,
					String adminId,String adminMobile){
			this.id=id;
			this.domain=domain;
			this.port=port;
			this.timeOut=timeOut;
			this.notifyTimes=notifyTimes;
			this.maxNotifyTimes=maxNotifyTimes;
			this.state=state;		
			this.adminId=adminId;
			this.adminMobile=adminMobile;
		}
	}
	/**   
	  *   读取属性完成初始化   
	  */   
	  private   void   init()   {   
			  InputStream   is   =   getClass().getResourceAsStream(fileName);   
			  Properties   props   =   new   Properties();   
			  try   {   
					  props.load(is);   
			  }   
			  catch   (Exception   e)   {   
					  System.err.println("不能读取属性文件.   "   +"请确保siteMonitor.properties在CLASSPATH指定的路径中");   
					  return;   
			  }   
 			  //String   logFile   =   props.getProperty("logfile");                     
			 logFileName   =   props.getProperty("logfilePath")+"siteMonitor.txt";           
			 
			  try   {   
			  		monitorInterval=Long.parseLong(props.getProperty("monitorInterval"));
					numberOfThreads=Integer.parseInt(props.getProperty("numberOfThreads"));
					//adMsg=props.getProperty("adMsg");
					adMsg=new String( (props.getProperty("adMsg")).getBytes("iso-8859-1"),"gb2312" );
					smsID=msg.Global.getParameter("smsID");//props.getProperty("smsID");					  
					String path=(((this.getClass()).getResource("")).getPath()).toString();		   
		  			//path 形如:/D:/100imserver/Tomcat5.5/webapps/ROOT/WEB-INF/classes/msg/		 			 
		  			path=path.substring(0,path.indexOf("WEB-INF")); 
					logFileName=path+"logs/"+props.getProperty("logfile");   
			  }   
			  catch   (Exception   e)   {   
					  System.err.println("无法打开日志文件:   "   +   logFile);   
					  //log   =   new   PrintWriter(System.err);   
			  }   
			  
 	  }   
	/**   
	  *   将文本信息写入日志文件   
	  */   
	  private   void   log(String   s)   {   
			  //log.println(new    java.util.Date()   +   ":   "   +   msg);   
		try{
 		   //如果文件大于5M,就把原log文件名+1,然后另立文件
		   File logFile=new File(logFileName);
		   if(logFile!=null && logFile.exists() && logFile.length() > 5*1024*1024 ) {  //如果文件大于5M
			  String filePre=logFileName.substring(0,logFileName.indexOf("."));
			  File f1;
			  for(int i=1;i>0;i++){
				f1=new File(filePre+String.valueOf(i)+".txt");
				if(f1.exists())
					continue;
				else{
				   logFile.renameTo(new File(filePre+String.valueOf(i)+".txt")); 
				   logFile=new File(logFileName);
				   logFW = new FileWriter(logFileName,true); //false 覆盖原有文件
				   logPW = new PrintWriter(logFW); 	
 				   break;
				}
			  }
		   }
		   if(logPW == null){
		   		logFile=new File(logFileName);
			 	logFW = new FileWriter(logFileName,true); //false 覆盖原有文件
				logPW = new PrintWriter(logFW); 				  
		   }
		   logPW.print(new java.util.Date()+" "+s);
		   logPW.print("\r\n"); 
		   logPW.flush();
		}catch(Exception e){System.out.println("writeLog:"+e);}
	  }   

	  /**   
	  *   将文本信息与异常写入日志文件   
	  */   
	  private   void   log(Throwable   e,   String   msg)   {   
			  //log.println(new   java.util.Date()   +   ":   "   +   msg);   
			  //e.printStackTrace(log);   
	  }   
 
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -