Spring retry without spring application

喜欢而已 提交于 2020-06-09 06:38:42

问题


I have a java application, which starts from the main class (not Spring boot application). And I want to use Spring retry to retry when a connection is lost. As I know I need to add @EnableRetry annotation above main class in Spring application and then use @Retryable above my method with retrying. But I think it will not work in the non-spring application. Is it possible to use spring retry in simple java application (not spring app)?


回答1:


I found that I can use RetryTemplate:

    RetryTemplate retryTemplate = new RetryTemplate();

    FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
    fixedBackOffPolicy.setBackOffPeriod(2000l);
    retryTemplate.setBackOffPolicy(fixedBackOffPolicy);

    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(5);
    retryTemplate.setRetryPolicy(retryPolicy);

    retryTemplate.execute(new RetryCallback<Void, Throwable>() {
            @Override
            public Void doWithRetry(RetryContext context) throws Throwable {
                // do some job
                if(context.getRetryCount() < 3){ // unexpected disconnection
                    log.error("connection failed");
                    throw new RuntimeException("retry exception"); 
                }
                System.out.println("RETRY" + context);
                return null;
            }
        });


来源:https://stackoverflow.com/questions/59299658/spring-retry-without-spring-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!