SpringBoot 重试机制
Retry重试机制,其实就是我们对一个请求进行多次重试,可以指定重试的相关参数,例如重试次数、间隔、重试线程数等等,什么异常情况下进行重试,如果达到指定上限可以进行具体的最终性失败处理。
•第一步引入依赖:
•第二步:@EnableRetry 启用重试功能
•第三步:@Retryable 在方法上配置重试机制,相关核心配置参数如下
•value 指定异常进行重试策略的执行
•maxAttempts 重试次数
•Backoff @Backoff(delay = 5000, multiplier = 5)) 重试间隔 线程并行度
•第四步:@Recover 最终失败处理方法
实现:
package com.cc.springboot.service;
import java.util.concurrent.TimeoutException;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
@EnableRetry
@Service
public class RetryService {
@Retryable(
//配置value什么类型异常进行重试
value = {RemoteAccessException.class,TimeoutException.class},
maxAttempts = 3, //重试次数
backoff = @Backoff(delay = 2000,multiplier = 5)
)
public void call() throws Exception{
System.out.println("执行了call方法...");
//RPC服务调用,(timeout...)
//不可能同时捕获两种异常,所以进行切换测试
//throw new RemoteAccessException("rpc调用异常...");
throw new TimeoutException("超时异常...");
}
//3次重试失败后的补充策略,实际环境中自定义异常,继承
@Recover
public void recover(RemoteAccessException re) {
System.out.println("最终重试失败,进行补偿:"+re.getMessage());
}
@Recover
public void recover(TimeoutException te) {
System.out.println("最终重试失败,进行补偿:"+te.getMessage());
}
}
package com.cc.springboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.cc.springboot.service.RetryService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Test
public void contextLoads() {
}
@Autowired
private RetryService retryService;
@Test
public void testRetry() throws Exception{
retryService.call();
}
}
输出结果: