Spring retry without spring application

后端 未结 1 815
北海茫月
北海茫月 2021-01-28 22:12

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

相关标签:
1条回答
  • 2021-01-28 23:06

    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;
                }
            });
    
    0 讨论(0)
提交回复
热议问题