'Apache 5 HttpClient Retry Strategy Not Working

I am trying to add a custom retry strategy to my HttpClient such that it retries on SocketTimeoutException and NoHttpResponseException. However, the custom retry strategy is not getting invoked in case of these errors. Please find the code snippets below:

Creating HttpClient:

    val requestConfig = RequestConfig.custom()
        .setConnectTimeout(Timeout.ofMilliseconds(20))
        .setResponseTimeout(Timeout.ofMilliseconds(1000))
        .setConnectionRequestTimeout(Timeout.ofMilliseconds(200))
        .build()

    val retryStrategy = CustomRetryStrategy(
        3, // Retry 3 times
        TimeValue.ofMilliseconds(10) // Retry very quickly
    )
    

    val client = HttpClientBuilder.create()
        .setDefaultRequestConfig(requestConfig)
        .setRetryStrategy(retryStrategy)
        .build()

Retry Strategy Code:


class CustomRetryStrategy(private val maxRetries: Int, private val defaultRetryInterval: TimeValue) :
    DefaultHttpRequestRetryStrategy(maxRetries, defaultRetryInterval) {

    override fun retryRequest(request: HttpRequest, exception: IOException, execCount: Int, context: HttpContext?): Boolean {
        if (execCount > this.maxRetries) {
            // Do not retry if over max retries
            return false
        }

        if (exception is SocketTimeoutException ||
            exception.cause is SocketTimeoutException ||
            exception.cause is NoHttpResponseException ||
            exception is NoHttpResponseException
        ) {
            println("Retryable Exception Encountered. Retrying")
            return true
        }
        return super.retryRequest(request, exception, execCount, context)
    }
}

Execute Request Code:

val response = client.execute(request)

May I know what am I missing or doing wrong which is leading to retries not getting executed?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source