简体   繁体   English

Spring重试异常块的问题

[英]Issue with Spring retry for Exception Block

I am trying to use retry https://www.mscharhag.com/spring/spring-retry but facing an issue. 我正在尝试使用重试https://www.mscharhag.com/spring/spring-retry,但遇到了问题。 I have a method 我有办法

public String methodA( T Object)  {
    try{

    }catch(someException sme){
       return fixit(Object);
    }
}

@Retryable(value = {someException.class}, maxAttempts = 3)
public String fixit( T Object)  {
    return x;
}

Where I need to try fixit 3 times if the same exception is thrown. 如果抛出相同的异常,我需要尝试3次fixit。 But somehow retryable is not working for a method I am calling from exception block. 但是某种程度上可重试对于我从异常块中调用的方法不起作用。

Any pointers of whats missing? 任何缺少什么的指针? If I add the annotation on top of methodA it works, but thats not the behaviour I want. 如果我在methodA顶部添加注释,则它可以工作,但这不是我想要的行为。 I tried @Recover,but it is called only after the maxAttempts is tried and not each time exception is hit. 我尝试了@Recover,但是只有在尝试了maxAttempts之后才调用它,而不是每次都遇到异常时才调用它。

I assume that @Retryable is working with AOP interceptors and Java proxies. 我假设@Retryable正在使用AOP拦截器和Java代理。

The issue you are facing is that you are calling a method within the same class and therefore the AOP proxy does not get involved. 您面临的问题是您正在同一类中调用方法,因此AOP代理不参与。 This is why your code starts to work as expected when you move the annotation to the method methodA (since I assume that method gets call from another class). 这就是为什么将注释移至methodA方法时代码开始按预期工作的原因(因为我假设该方法从另一个类调用)。

What you can do is move your method fixit to another Spring bean and inject it into the Spring bean with methodA 您可以做的是将方法fixit移至另一个Spring bean,并使用methodA将其注入到Spring bean中。

@Component
class ClassWithMethodA {

  @Autowired
  private AnotherBean bean;

  public String methodA( T o)  {
    try{

    }catch(someException sme){
       return bean.fixit(o);
    }
  }
}

@Component
class AnotherBean {
  @Retryable(value = {someException.class}, maxAttempts = 3)
  public String fixit( T o)  {
    return x;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM