注释不起作用的Spring重试框架

时间:2016-10-28 15:09:02

标签: java spring-retry

我使用SimpleRetryPolicy / RetryTemplate尝试使用Simple java类的spring retry框架。它工作正常。所以我想用Annotations做同样的事情。注释从来没有对我有用。没有在网上找到很多帮助。下面的代码就像普通的Java程序一样,在第一次尝试时抛出异常,这不是预期的行为。在抛出异常或从中恢复之前,它应该至少试过5次。不知道我哪里出错了。我是否需要执行任何XML / spring AOP配置才能工作?怎么会

import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;

@EnableRetry
@Configuration
public class App {  
    public static void main(String[] args) throws Exception {
        Parentservice p = new  SpringRetryWithHystrixService();
        String status = p.getStatus();
        System.out.println(status);
    }
}

import org.springframework.retry.annotation.Retryable;
public interface Parentservice {
    @Retryable(maxAttempts=5)
    String getStatus() throws Exception;
}


import org.springframework.retry.annotation.Recover;
public class SpringRetryWithHystrixService implements Parentservice{

    public static int i=0;

    public String getStatus() throws Exception{
        System.out.println("Attempt:"+i++);
        throw new NullPointerException();
    }

        @Recover
        public static String getRecoveryStatus(){
            return "Recovered from NullPointer Exception";
        }
    }

我在界面和实现的顶部尝试了@Retryable(maxAttempts = 5),但没有任何区别。

2 个答案:

答案 0 :(得分:6)

您的申请必须由Spring管理,您不能只使用new ...

Parentservice p = new  SpringRetryWithHystrixService();

这是一个Spring Boot应用程序......

@SpringBootApplication
@EnableRetry
public class So40308025Application {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = SpringApplication.run(So40308025Application.class, args);
        System.out.println(context.getBean(SpringRetryWithHystrixService.class).getStatus());
        context.close();
    }

}


@Component
public class SpringRetryWithHystrixService {

    public static int i = 0;

    @Retryable(maxAttempts = 5)
    public String getStatus() throws Exception {
        System.out.println("Attempt:" + i++);
        throw new NullPointerException();
    }

    @Recover
    public static String getRecoveryStatus() {
        return "Recovered from NullPointer Exception";
    }

}

结果:

Attempt:0
Attempt:1
Attempt:2
Attempt:3
Attempt:4
Recovered from NullPointer Exception

如果您因某些原因不想使用Spring Boot,请使用

@Configuration
@EnableRetry
public class So40308025Application {

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(So40308025Application.class);
        System.out.println(context.getBean(SpringRetryWithHystrixService.class).getStatus());
        context.close();
    }

    @Bean
    public SpringRetryWithHystrixService service() {
        return new SpringRetryWithHystrixService();
    }

}

答案 1 :(得分:0)

就我而言,我必须删除@EnableRetry批注才能使其正常工作。