2011-04-20 54 views
1

不斷監控http請求,如果返回代碼200則不採取任何操作,但如果返回404,則應通過警告或郵件通知管理員。執行創建報告方法,通過郵件向管理員報告

我想知道如何從Java的角度來看待它。可用的代碼不是很有用。

+3

可用的?你做什麼*不是*想要?你試過什麼了?而Java≠JavaScript。順便說一句,你不能從JavaScript內發送郵件,你也需要一個服務器端腳本。 – 2011-04-20 09:57:16

+1

我想要一個使用Java的常量http請求監視器,如果返回的代碼是404,那麼我希望程序向該站點的管理員發送郵件。對不起,錯誤地提出了這個問題 – KronnorK 2011-04-24 17:37:53

+0

然後這個問題根本不涉及到JavaScript。而且你看到哪些代碼原來不是很有用? – 2011-04-24 18:51:23

回答

2

首先,你應該考慮使用現有的工具,這個工作(例如Nagios等)。否則,你可能會發現自己重寫了很多相同的功能。一旦檢測到問題,您可能只想發送一封電子郵件,否則您會向管理員發送垃圾郵件。同樣,您也許希望在發送警報之前等待第二次或第三次失敗,否則可能會發送錯誤警報。現有的工具確實可以處理這些事情,而且更適合您。

也就是說,你特別要求的東西在Java中並不太難。以下是一個簡單的工作示例,可以幫助您開始。它通過每30秒發出一次請求來監控一個URL。如果它檢測到狀態碼404,它會發送一封電子郵件。它取決於JavaMail API並且需要Java 5或更高版本。

public class UrlMonitor implements Runnable { 
    public static void main(String[] args) throws Exception { 
     URL url = new URL("http://www.example.com/"); 
     Runnable monitor = new UrlMonitor(url); 
     ScheduledExecutorService service = Executors.newScheduledThreadPool(1); 
     service.scheduleWithFixedDelay(monitor, 0, 30, TimeUnit.SECONDS); 
    } 

    private final URL url; 

    public UrlMonitor(URL url) { 
     this.url = url; 
    } 

    public void run() { 
     try { 
      HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
      if (con.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { 
       sendAlertEmail(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    private void sendAlertEmail() { 
     try { 
      Properties props = new Properties(); 
      props.setProperty("mail.transport.protocol", "smtp"); 
      props.setProperty("mail.host", "smtp.example.com"); 

      Session session = Session.getDefaultInstance(props, null); 
      Message message = new MimeMessage(session); 
      message.setFrom(new InternetAddress("[email protected]", "Monitor")); 
      message.addRecipient(Message.RecipientType.TO, 
        new InternetAddress("[email protected]")); 
      message.setSubject("Alert!"); 
      message.setText("Alert!"); 

      Transport.send(message); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

我討厭這樣說,但我認爲你更喜歡我的:) – extraneon 2011-04-24 20:23:13

1

我會從石英調度程序開始,創建一個SimpleTrigger。 SimpleTrigger將使用httpclient創建連接,並在出現意外的答案時使用JavaMail API發送郵件。我可能使用彈簧來連接它,因爲它具有良好的石英集成,並且允許簡單的模擬實現進行測試。

快速和污垢例如無彈簧結合石英和HttpClient的(用來爲JavaMail見How do I send an e-mail in Java?):

進口(所以你知道我從班):

import java.io.IOException; 
import org.apache.http.HttpResponse; 
import org.apache.http.StatusLine; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.quartz.Job; 
import org.quartz.JobExecutionContext; 
import org.quartz.JobExecutionException; 

代碼:

public class CheckJob implements Job { 
    public static final String PROP_URL_TO_CHECK = "URL"; 

    public void execute(JobExecutionContext context) 
         throws JobExecutionException { 
     String url = context.getJobDetail().getJobDataMap() 
          .getString(PROP_URL_TO_CHECK); 
     System.out.println("Starting execution with URL: " + url); 
     if (url == null) { 
      throw new IllegalStateException("No URL in JobDataMap"); 
     } 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet get = new HttpGet(url); 
     try { 
      processResponse(client.execute(get)); 
     } catch (ClientProtocolException e) { 
      mailError("Got a protocol exception " + e); 
      return; 
     } catch (IOException e) { 
      mailError("got an IO exception " + e); 
      return; 
     } 

    } 

    private void processResponse(HttpResponse response) { 
     StatusLine status = response.getStatusLine(); 
     int statusCode = status.getStatusCode(); 
     System.out.println("Received status code " + statusCode); 
     // You may wish a better check with more valid codes! 
     if (statusCode <= 200 || statusCode >= 300) { 
      mailError("Expected OK status code (between 200 and 300) but got " + statusCode); 
     } 
    } 

    private void mailError(String message) { 
     // See https://stackoverflow.com/questions/884943/how-do-i-send-an-e-mail-in-java 
    } 
} 

和它運行永遠主類,並檢查每2分鐘:

進口:

import org.quartz.JobDetail; 
import org.quartz.SchedulerException; 
import org.quartz.SchedulerFactory; 
import org.quartz.SimpleScheduleBuilder; 
import org.quartz.SimpleTrigger; 
import org.quartz.TriggerBuilder; 
import org.quartz.impl.StdSchedulerFactory; 

代碼:

public class Main { 

    public static void main(String[] args) { 
     JobDetail detail = JobBuilder.newJob(CheckJob.class) 
          .withIdentity("CheckJob").build(); 
     detail.getJobDataMap().put(CheckJob.PROP_URL_TO_CHECK, 
            "http://www.google.com"); 

     SimpleTrigger trigger = TriggerBuilder.newTrigger() 
       .withSchedule(SimpleScheduleBuilder 
       .repeatMinutelyForever(2)).build(); 


     SchedulerFactory fac = new StdSchedulerFactory(); 
     try { 
      fac.getScheduler().scheduleJob(detail, trigger); 
      fac.getScheduler().start(); 
     } catch (SchedulerException e) { 
      throw new RuntimeException(e); 
     } 
    } 
}