2011-04-20 2 views
1

코드 200을 반환하고 아무런 조치도 취하지 않지만 404가 반환되면 관리자에게 경고 또는 메일로 경고해야하는 http 요청을 지속적으로 모니터링합니다.메일을 통해 관리자에게보고하는보고 방법론을 구현하는 구현

Java 관점에서 접근하는 방법을 알고 싶었습니다. 사용 가능한 코드는별로 유용하지 않습니다.

+3

어디에서 사용할 수 있습니까? 너는 무엇을하고 * 원하지 않니? 지금까지 뭐 해봤 어? 그리고 Java ≠ JavaScript. BTW, 당신은 자바 스크립트 내에서 메일을 보낼 수 없습니다, 당신은 그것을 위해 서버 측 스크립트가 필요합니다. –

+1

Java를 사용하여 지속적인 HTTP 요청 모니터를 원했고 반환 된 코드가 404라면 프로그램이 사이트의 관리자에게 메일을 보내길 원했습니다. 잘못 질문을 퍼붓기 죄송합니다 – KronnorK

+0

다음이 질문은 JavaScript와 전혀 관련이 없습니다. 그리고 어떤 코드를 보면 그렇게 유용하지 않은 것으로 나타 났습니까? –

답변

2

첫째, 당신은이 작업을 위해 설계된 기존의 도구를 사용하는 것이 좋습니다 (예를 들어, Nagios 등). 그렇지 않으면 같은 기능을 많이 재 작성하는 경향이 있습니다. 문제가 발견되면 이메일 하나만 보내고 싶지 않을 경우 관리자에게 스팸 메일을 보냅니다. 마찬가지로 경고를 보내기 전에 두 번째 또는 세 번째 오류가 발생할 때까지 기다려야 할 수도 있습니다. 그렇지 않으면 잘못된 경보를 보낼 수 있습니다. 기존 도구가 이러한 기능을 처리하고 더 많은 기능을 제공합니다.

즉, 구체적으로 물어 본 것은 Java에서 그리 어렵지 않습니다. 아래는 시작하는 데 도움이되는 간단한 작업 예제입니다. 30 초마다 URL을 요청하여 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

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); 
     } 
    } 
} 
관련 문제