简体   繁体   中英

RetryTemplate is only Executing Once

In the below method i am using the retry logic, what i am expecting for the first try it should fail, for the second one it's should successfully save.

public Record saveRecord(Record Record) {
            try {
                return vcRetry.execute(
                        context -> {
                            System.out.println("Inside the Method");
                            if(context.getRetryCount()==0)
                            throw new RuntimeException("Something went wrong");
                            return RecordDao.save(Record);
                        });

The above method is executing only one time, i had done some debugging the vcRetry template properties are correct : 在此处输入图片说明

Please help why it's not coming back the second time ?

I tried your code, it worked well. but you set backOffPeriod to 12 seconds. Maybe you should be more patient((12 seconds)) to get your second call. Please change your backOffPeriod to 2 seconds and try again.

I coded your scenario as follows:

Create RetryTemplate

@Configuration
public class Config {

@Bean
public RetryTemplate retryTemplate() {

    RetryTemplate retryTemplate = new RetryTemplate();

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

    //Retry Policy
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(2);
    retryTemplate.setRetryPolicy(retryPolicy);

    return retryTemplate;

    }
}

Use retryTemplate in TestService

@Service
public class TestService {

@Autowired
private RetryTemplate retryTemplate;

public String testService() {

    //Retryable
    String result = retryTemplate.execute(context -> {
        System.out.println("Inside the Method, Retry = " + context.getRetryCount());
        if (context.getRetryCount() == 0)
            throw new RuntimeException("Something went wrong");
        return "Successfully Completed";
    });

    //Result
    System.out.println("FINAL Result = " + result);
    return result;
  }
}  

Result in console :

Inside the Method, Retry = 0

Inside the Method, Retry = 1

FINAL Result = Successfully Completed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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