在云计算世界中,至关重要的部分之一就是网络,事实是我们无法避免出现网络故障,并且会暂时断开连接几秒钟,这使得从本地云中进行与网络相关的配置时操作会中断应用程序。我将用spring-context讨论Java中的一种解决方案,有关如何使用Spring Retry Template处理失败操作。我们将构建一个小应用程序,并查看Spring Retry Template的工作方式。
Pre-Requisites
Maven依赖
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
创建Spring Retry模板Bean
@Configuration
@EnableRetry
public class BeanSeederServices {
@Bean
public RetryTemplate retryTemplate() {
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(4);
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(3000);
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(retryPolicy);
template.setBackOffPolicy(backOffPolicy);
return template;
}
}
创建一个bean配置类来管理所需的bean,使用@EnableRetry批注启用spring retry并创建RetryTemplate bean,以便可以在整个spring boot应用程序中使用此bean重试失败的操作。我们已使用SimpleRetryPolicy将最大重试次数配置为4,并且背对背重试会导致资源锁定,因此我们应该添加BackOff策略以在重试之间创建间隔。
默认情况下,每个操作最多重试3次,而两次操作之间没有任何回退。
将可重试逻辑放入服务中
@Service
public class ConfigureNetworkService
{
@Autowired
private RetryTemplate retryTemplate;
int counter =0;
private void configureNetworkSystem(){
retryTemplate.execute(
context -> {
verifyNwConfiguration();
return true;
});
}
private void verifyNwConfiguration(){
counter++;
LOGGER.info("N/W configuration Service Failed "+ counter);
throw new RuntimeException();
}
}
Execute块将继续执行回调,直到成功执行或策略指示我们停止为止,在这种情况下,回调引发的最新异常将被重新抛出。
创建一个REST端点进行测试
创建此客户端的目的只是为了击中ConfigureNetworkService configureNetworkSystem()方法。
@RestController
@RequestMapping(value="/networksrv")
public class NetworkClientService {
@Autowired
private ConfigureNetworkService configureNetworkService;
@GetMapping
public String callRetryService() throws SQLException {
return configureNetworkService.configureNetworkSystem();
}
}
启动URL并查看日志 http:// localhost:8080 / networksrv
2020-06-16 09:59:51.399 INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService : N/W configuration Service Failed 1
2020-06-16 09:59:52.401 INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService : N/W configuration Service Failed 2
2020-06-16 09:59:53.401 INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService : N/W configuration Service Failed 3
2020-06-16 09:59:53.402 INFO 17288 --- [nio-8080-exec-1] c.e.springretrydemo.NetworkClientService : N/W configuration Service Failed 4
Exception in thread "NetworkClientService" java.lang.RuntimeException
日志显示它已经尝试了simpleRetry方法4次,然后抛出Runtime异常。
这是从该博客中学到的东西。让我知道其他框架或其他技术可行性,以重试失败的操作。
原文链接:http://codingdict.com