如果主机离线,重试 java RestTemplate HTTP 请求 [英] Retry java RestTemplate HTTP request if host offline

查看:32
本文介绍了如果主机离线,重试 java RestTemplate HTTP 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 spring RestTemplate 来调用 REST API.API 可能非常慢,甚至离线.我的应用程序通过一个接一个地发送数千个请求来构建缓存.响应也可能很慢,因为它们包含大量数据.

Hi I'm using the spring RestTemplate for calling a REST API. The API can be very slow or even offline. My application is building the cache by sending thousands of requests one after the other. The responses can be very slow too, because they contains a lot of data.

我已经将超时时间增加到 120 秒.我现在的问题是 API 可以离线,并且我收到 org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool 异常.

I have already increased the Timeout to 120 seconds. My problem now it that the API can be offline and I get a org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool exception.

在 API 离线的情况下,应用程序应等待并重试,直到 API 再次在线.

In the case when the API ist offline, the application should wait and try again until the API is online again.

我可以在 RestTemplate 中实现这一点,而无需自己构建异常循环吗?

Can I achieve this in RestTemplate out of the box without building exception-loops on my own?

谢谢!

推荐答案

我遇到了同样的情况,通过谷歌搜索找到了解决方案.给出答案,希望对其他人有所帮助.您可以设置每次尝试的最大尝试次数和时间间隔.

I had same situation and done some googling found the solution. Giving answer in hope it help someone else. You can set max try and time interval for each try.

@Bean
  public RetryTemplate retryTemplate() {

    int maxAttempt = Integer.parseInt(env.getProperty("maxAttempt"));
    int retryTimeInterval = Integer.parseInt(env.getProperty("retryTimeInterval"));

    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(maxAttempt);

    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(retryTimeInterval); // 1.5 seconds

    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy);
    template.setBackOffPolicy(backOffPolicy);

    return template;
  }

我要执行的休息服务如下.

And my rest service that i want to execute is below.

retryTemplate.execute(context -> {
        System.out.println("inside retry method");
        ResponseEntity<?> requestData = RestTemplateProvider.getInstance().postAsNewRequest(bundle, ServiceResponse.class, serivceURL,
                CommonUtils.getHeader("APP_Name"));

        _LOGGER.info("Response ..."+ requestData);
            throw new IllegalStateException("Something went wrong");
        });

这篇关于如果主机离线,重试 java RestTemplate HTTP 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆