实施创建报告方法以通过邮件向管理员报告

时间:2011-04-20 09:56:30

标签: java http heartbeat

持续监控http请求,如果返回代码200,则不执行任何操作,但如果返回404则应通过警告或邮件提醒管理员。

我想知道如何从Java角度来处理它。可用的代码不是很有用。

2 个答案:

答案 0 :(得分: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("me@example.com", "Monitor"));
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress("me@example.com"));
            message.setSubject("Alert!");
            message.setText("Alert!");

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

答案 1 :(得分:1)

我将从quartz调度程序开始,并创建一个SimpleTrigger。 SimpleTrigger将使用httpclient创建连接,并在发生意外答案时使用JavaMail api发送邮件。我可能使用spring连接它,因为它具有良好的石英集成,并允许简单的模拟实现进行测试。

没有弹簧结合Quartz和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);
        }
    }
}