[java] HttpClient를 사용하여 웹 서버와의 연결에서 Timeout 발생 시에 재시도하는 방법은?
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
public class RetryOnTimeoutExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClients.custom()
.setRetryHandler((exception, executionCount, context) -> {
if (executionCount > 3) {
return false; // 최대 3번까지 재시도
}
if (exception instanceof InterruptedIOException) {
return true; // Timeout 발생 시 재시도
}
return false;
})
.build();
HttpGet httpGet = new HttpGet("http://example.com");
try {
httpClient.execute(httpGet);
// HTTP 요청 성공 처리
} catch (IOException e) {
e.printStackTrace();
// 재시도 실패로 인한 예외 처리
}
}
}
위의 예제에서는 HttpClient의 setRetryHandler
메서드를 사용하여 Timeout 발생 시에 재시도를 수행합니다. RetryHandler
의 구현에서는 executionCount
를 통해 현재 재시도 횟수를 확인하고, exception
이 InterruptedIOException
인지 확인하여 Timeout 상황을 감지합니다. 최대 3번까지 재시도하며, 재시도가 불가능하면 false
를 반환하여 중단합니다.
해당 예제에서는 httpGet
을 통해 실제로 HTTP GET 요청을 수행하는 부분이 포함되어 있으며, 요청에 실패했을 경우 예외 처리를 수행하도록 되어 있습니다.
이 예제를 통해 HttpClient를 사용하여 Timeout 발생 시에 재시도하는 방법을 구현할 수 있습니다.