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

发布于 2024-11-02 10:53:23 字数 109 浏览 0 评论 0原文

持续监控 http 请求,如果返回代码 200,则不采取任何操作,但如果返回 404,则应通过警告或邮件向管理员发出警报。

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

Constantly monitor a http request which if returns code 200 then no action is taken but if a 404 is returned then the administrator should be alerted via warning or mail.

I wanted to know how to approach it from a Java perspective. The codes available are not very useful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

断桥再见 2024-11-09 10:53:23

首先,您应该考虑使用专为这项工作设计的现有工具(例如 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();
        }
    }
}

First of all, you should consider using an existing tool designed for this job (e.g. Nagios or the like). Otherwise you'll likely find yourself rewriting many of the same features. You probably want to send only one email once a problem has been detected, otherwise you'll spam the admin. Likewise you might want to wait until the second or third failure before sending an alert, otherwise you could be sending false alarms. Existing tools do handle these things and more for you.

That said, what you specifically asked for isn't too difficult in Java. Below is a simple working example that should help you get started. It monitors a URL by making a request to it every 30 seconds. If it detects a status code 404 it'll send out an email. It depends on the JavaMail API and requires Java 5 or higher.

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();
        }
    }
}
我纯我任性 2024-11-09 10:53:23

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

一个快速而肮脏的例子,没有 spring 结合 Quartz 和 HttpClient (对于 JavaMail 参见 我如何用 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);
        }
    }
}

I'd start with the quartz scheduler, and create a SimpleTrigger. The SimpleTrigger would use httpclient to create connection and use the JavaMail api to send the mail if an unexpected answer occurred. I'd probably wire it using spring as that has good quartz integration and would allow simple mock implementations for testing.

A quick and dirt example without spring combining Quartz and HttpClient (for JavaMail see How do I send an e-mail in Java?):

imports (so you know where I got the classes from):

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;

code:

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
    }
}

and the main class which runs forever and checks every 2 minutes:

imports:

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;

code:

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);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文