コード 200 が返された場合はアクションは実行されませんが、404 が返された場合は、管理者に警告またはメールで警告する必要がある http 要求を常に監視します。
Javaの観点からアプローチする方法を知りたかったのです。利用可能なコードはあまり役に立ちません。
まず、この作業用に設計された既存のツール ( Nagiosなど) の使用を検討する必要があります。そうしないと、同じ機能の多くを書き直すことになるでしょう。問題が検出されたら、おそらく 1 通の電子メールのみを送信する必要があります。そうしないと、管理者にスパムが送信されます。同様に、アラートを送信する前に 2 回目または 3 回目の障害が発生するまで待ちたい場合があります。そうしないと、誤ったアラームを送信する可能性があります。既存のツールは、これらのことなどを処理します。
とはいえ、あなたが具体的に要求したことは、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();
}
}
}
Quartz スケジューラーから始めて、SimpleTrigger を作成します。SimpleTrigger は httpclient を使用して接続を作成し、予期しない応答が発生した場合は JavaMail API を使用してメールを送信します。クォーツとの統合が良好で、テスト用の単純なモック実装が可能になるため、おそらく春を使用して配線します。
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);
}
}
}