最近研究了一下spring-retry框架地使用。
spring-retry再1.3.0版中@Retryable增加recover属性,从而使得再异常重试失败后可以指定补偿方法执行。
从而使得我们不需要每一个用到@Recover的地方都需要新建一个类。
@Retryable(recover = "compensateHi")
@Override
public Hello hi(String name) {
try {
Hello hello = helloClient.hi(name);
return hello;
}catch (Exception e){
e.printStackTrace();
throw new MyHttpExcetption("");
}
}
@Recover
//Throwable throwable必须写,否则无法匹配
private Hello compensateHi(Throwable throwable,String name) {
System.out.println("compensateHi");
try {
Hello hello = helloRepository.findByName(name);
return hello;
}catch (Exception e){
throw new MyHttpExcetption("");
}
}
@Recover
//Throwable throwable必须写,否则无法匹配
private Hello compensateHi2(Throwable throwable,String name) {
System.out.println("compensateHi2");
try {
Hello hello = helloRepository.findByName(name);
return hello;
}catch (Exception e){
throw new MyHttpExcetption("");
}
}
但是要注意的是,在异常重试失败进行匹配是,方法的第一个参数必须是Throwable或其子类,否则就算@Retryable中recover属性指定也无法匹配。