没有 Spring 应用的 Spring 重试

Val*_* K. 2 java spring-retry

我有一个java应用程序,它从主类(不是Spring boot应用程序)开始。我想使用 Spring retry 在连接丢失时重试。据我所知,我需要在 Spring 应用程序中的主类上方添加 @EnableRetry 注释,然后在我的方法上方使用 @Retryable 进行重试。但我认为它在非 spring 应用程序中不起作用。是否可以在简单的java应用程序(不是spring应用程序)中使用spring重试?

Val*_* K. 8

我发现我可以使用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;
            }
        });
Run Code Online (Sandbox Code Playgroud)