重试的依赖
<!-- spring重试-->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
使用@Retryable需要在程序入口类上使用@EnableRetry注解开启重试功能
@Retryable(value = Exception.class, maxAttemptsExpression = "${Retry.maxRetryTime}", backoff = @Backoff(delay = 2000L, multiplier = 1.5))
public List<IaqAirsettingMappingDto> httpPost(Integer currentPage, Integer pageSize) throws Exception {
log.info("请求第{}页,每页最大数据量{}", currentPage, pageSize);
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http POST请求
HttpPost httpPost = new HttpPost(httpClientConfig.URL);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(httpClientConfig.getConnectTimeout())
.setSocketTimeout(httpClientConfig.getSocketTimeout()).build();
httpPost.setConfig(requestConfig);
String parameters = "{\"currentPage\":" + currentPage + ',' + "\"pageSize\":" + pageSize + "}";
StringEntity entity = new StringEntity(parameters, "utf-8");
// 将请求实体设置到httpPost对象中
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
List<IaqAirsettingMappingDto> list = null;
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
JSONObject jsStr = JSONObject.parseObject(content);
// 获取到返回值,转为json字符串
String jsonString = jsStr.getJSONObject("data")
.getJSONArray("airsettingMappingDtoList").toJSONString();
list = JSON.parseArray(jsonString, IaqAirsettingMappingDto.class);
} else {
log.error("请求代理服务器失败,状态码:{}", response.getStatusLine().getStatusCode());
throw new HttpClientException("请求代理服务器错误");
}
return list;
}
@Retryable的value指定出现某个异常时进行重试,maxAttempts可以直接指定重试次数(maxAttempts=实际重试次数+1),使用maxAttemptsExpression 也可以指定重试次数,如果使用这个方法,则可以通过从yml文件中获取数据.
backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒
注意点:
@Retryable指定的方法有异常直接抛出,如果try catch则会出现无法重试的情况.
@Retryable标注的方法和它的调用者不能在同一个类中
@Retryable可以使用@Recover来在重试次数用完还没有成功时执行,据其他博客说,需要和@Retryable的方法返回值一样才行…