实施创建报告方法以通过邮件向管理员报告
持续监控 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您应该考虑使用专为这项工作设计的现有工具(例如 Nagios 等)。否则,您可能会发现自己重写了许多相同的功能。一旦检测到问题,您可能只想发送一封电子邮件,否则您将向管理员发送垃圾邮件。同样,您可能需要等到第二次或第三次失败后再发送警报,否则您可能会发送错误警报。现有的工具确实可以为您处理这些事情以及更多事情。
也就是说,您具体要求的内容在 Java 中并不太难。下面是一个简单的工作示例,可以帮助您入门。它通过每 30 秒向 URL 发出一次请求来监视该 URL。如果检测到状态代码 404,它将发送一封电子邮件。它取决于 JavaMail API 并且需要 Java 5 或更高版本。
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.
我将从quartz调度程序开始,并创建一个SimpleTrigger。 SimpleTrigger 将使用 httpclient 创建连接,并在出现意外应答时使用 JavaMail api 发送邮件。我可能会使用 spring 连接它,因为它具有良好的石英集成,并且允许简单的模拟实现进行测试。
一个快速而肮脏的例子,没有 spring 结合 Quartz 和 HttpClient (对于 JavaMail 参见 我如何用 Java 发送电子邮件?):
导入(这样你就知道我从哪里获取类):
代码:
以及永久运行并每 2 分钟检查一次的主类:
导入:
代码:
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):
code:
and the main class which runs forever and checks every 2 minutes:
imports:
code: