HttpClient でウェイト付きリトライを行う。
HttpClientでリトライ処理を行う場合通常は、「org.apache.commons.httpclient.DefaultHttpMethodRetryHandler」を使う。このDefaultHttpMethodRetryHandlerはリクエスト中にIOExceptionが発生した場合に、リトライ対応がされる。
このとき、DefaultHttpMethodRetryHandlerでは失敗したら直ぐにアクセスが行われるので短い間隔でアクセスすることになる。負荷を分散させるために、待ち状態を作りアクセスする場合は以下のようにするといい。
HttpClient client = new HttpClient(); //リクエストの作成(5回リトライ) GetMethod method = new GetMethod(url); DefaultHttpMethodRetryHandler handler = null; handler = new DefaultHttpMethodRetryHandler(5, false) { @Override public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) { boolean retry = super.retryMethod(method, exception, executionCount); if (retry) { try { Thread.sleep(500); } catch (InterruptedException e) { } } return retry; } }; method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, handler); try { client.executeMethod(method); } catch (HttpException e1) { log.warn("HttpException", e1); return; } catch (IOException e1) { log.warn("IOException", e1); return; }
retryMethodをオーバライドしてウェイトを挟めば問題解決!