Using spring retry to implement retry mechanism

Posted by Duncan85 on Sat, 07 Dec 2019 17:34:34 +0100

We often encounter some scenarios that need to retry the current operation, such as: file upload failure, re upload; wechat access token acquisition failure, re acquisition and so on. Today, let's talk about a toolkit that can implement this mechanism: Spring retry.

As shown in the figure, you can see that the latest version of spring retry is 1.2.2.RELEASE. This tool customizes the retry operation template, and you can set retry policy and fallback policy. At the same time, retry the execution instance to ensure thread safety.

If you use it, first introduce the shelf package:

<!-- https://mvnrepository.com/artifact/org.springframework.retry/spring-retry -->
<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>1.2.2.RELEASE</version>
</dependency>

Specific code implementation:

         // Build retry template instance
		RetryTemplate retry=new RetryTemplate();
		//Set retry policy, mainly set retry times
		SimpleRetryPolicy srp = new SimpleRetryPolicy(); 
		srp.setMaxAttempts(3);// Retry 3 times 
		//Set retry fallback operation policy, mainly set retry interval time
		FixedBackOffPolicy fbop = new FixedBackOffPolicy();
		fbop.setBackOffPeriod(2000);//Retry interval 2s, in ms
		retry.setRetryPolicy(srp);
		retry.setBackOffPolicy(fbop);
		
		//Retryer, return true after retrying successfully
		final RetryCallback<Object, Exception> dmReCall=new RetryCallback<Object, Exception>(){
			@Override 
			public Object doWithRetry(RetryContext context) throws Exception {// Start retrying 
				//Fill in the logic code to retry here
				System.out.println("do some thing");
                 //Specifies the state in which an exception occurs before a retry
                 if(true){

                      throw new RuntimeException();//Note here that the root cause of retry is to throw an exception
                   }
                                
				return null; //The data returned after success can be any data type
			}
		};
		//After the retry fails, execute-
		final RecoveryCallback<Object> rvcb=new RecoveryCallback<Object>(){
			@Override 
			public Object recover(RetryContext context) throws Exception { // Failed after multiple retries 
			        //Here you can add the last failed code logic	
                    logger.info("------- RecoveryCallback --------");
				return false; //The data returned after retry failure can be any data type
			} 
		};
		//Delete menu retry mechanism start
		try {
			
			Object obj = retry.execute(dmReCall,rvcb);
			//Here you can judge whether the retry is successful or failed according to the data of obj.
			System.out.println("do some obj");
		} catch (Exception e) {
			//error
		}

RetryTemplate takes on the role of retry performer. It can set simple retrypolicy (retry policy, upper limit of retry, root entity of retry) and fixed backoff policy (fixed backoff policy, time interval of retry backoff). RetryTemplate submits the operation through execute. It needs to prepare two class instances, RetryCallback and RecoveryCallback. The former corresponds to the logical instance of retrying callback and wraps the normal function operation. RecoveryCallback implements the recovery operation instance at the end of the whole operation. At the same time, the execute of RetryTemplate is thread safe.

If you need retry mechanism, you can try this tool.

Topics: Spring