Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the retry mechanism in Spring

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to use the retry mechanism in Spring". In daily operation, I believe many people have doubts about how to use the retry mechanism in Spring. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the retry mechanism in Spring". Next, please follow the editor to study!

Background

Retry, in fact, we need it a lot of times, in order to ensure fault tolerance, usability, consistency and so on. It is generally used to deal with some unexpected returns and exceptions of the external system, especially the network delay, interruption and so on. In addition, in the popular micro-service governance framework, there are usually their own retry and timeout configurations. For example, dubbo can set the retries=1,timeout=500 call to be retried only once, and the call fails if the 500ms call is not returned.

If we want to retry, to retry for a specific operation, we have to hard-code, probably the logic is basically to write a loop, count the number of failures according to the return or exception, and then set the exit condition. Doing so, not to mention writing such similar code for every operation, and mixing retry logic with business logic creates trouble for maintenance and extension.

From an object-oriented point of view, we should separate the retried code.

Introduction to use

Basic use

Let me give you an example:

@ Configuration @ EnableRetry public class Application {@ Bean public RetryService retryService () {return new RetryService ();} public static void main (String [] args) throws Exception {ApplicationContext applicationContext = new AnnotationConfigApplicationContext ("springretry"); RetryService service1 = applicationContext.getBean ("service", RetryService.class); service1.service () } @ Service ("service") public class RetryService {@ Retryable (value = IllegalAccessException.class, maxAttempts = 5, backoff= @ Backoff (value = 1500, maxDelay = 100000, multiplier = 1.2) public void service () throws IllegalAccessException {System.out.println ("service method..."); throw new IllegalAccessException ("manual exception") @ Recover public void recover (IllegalAccessException e) {System.out.println ("service retry after Recover = >" + e.getMessage ());}}

@ EnableRetry-indicates that the retry mechanism is enabled

@ Retryable-indicates that the method needs to be retried and has a wealth of parameters to meet your need for retry

@ Backoff-indicates the Backoff policy in retry

@ Recover-backtracking method, that is, this method will be executed if it fails after many retries

Spring-Retry is rich in its retry strategy and Backoff strategy, as well as operations such as backing, listeners and so on.

Then the parameters in each annotation are very simple. You can see what it means and how to use it. I won't say much about it. Follow the official account Java technology stack, reply in the background: spring, you can get my Spring series of tutorials, very complete.

Retry strategy

Take a look at some of the retry strategies that come with Spring Retry, which are mainly used to determine whether you need to retry when a method call is abnormal. (the following principles will be analyzed and implemented in depth.)

SimpleRetryPolicy retries up to 3 times by default

TimeoutRetryPolicy retries if it fails within 1 second by default.

If ExpressionRetryPolicy matches the expression, it will try again.

CircuitBreakerRetryPolicy adds a circuit breaker mechanism, which allows retry if it is not in the circuit breaker state.

CompositeRetryPolicy can combine multiple retry strategies

NeverRetryPolicy never retries (is also a retry strategy)

AlwaysRetryPolicy always retries.

... . Wait

Backoff strategy

Take a look at the Backoff strategy, Backoff refers to how to do the next retry, here is actually how long to wait. (the following principles will be analyzed and implemented in depth.)

FixedBackOffPolicy performs the next retry after a fixed delay of 1 second by default

ExponentialBackOffPolicy exponentially increases the delay to perform a retry. The default initial delay is 0.1s, and the coefficient is 2. Then the next delay is 0.2s, then the next delay is 0.4s, and so on, a maximum of 30 seconds.

ExponentialRandomBackOffPolicy adds randomness to the above strategy

The difference between UniformRandomBackOffPolicy and the above is that the above delay will continue to increase, and this will only be random in a fixed interval.

The description of StatelessBackOffPolicy is stateless. Statelessness means being unaware of the last Backoff, as can be seen from the subclasses below it.

Principle

The principle part is divided into two parts: one is the entry point of the retry mechanism, that is, how it enables your code to achieve the retry function; the other is the details of the retry mechanism, including the logic of retry and the implementation of retry strategy and Backoff strategy. In addition, follow the official account Java technology stack, reply in the background: interview, you can get my Spring series of interview questions and answers, very complete.

Entry point

@ EnableRetry

Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ EnableAspectJAutoProxy (proxyTargetClass = false) @ Import (RetryConfiguration.class) @ Documented public @ interface EnableRetry {/ * * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed * to standard Java interface-based proxies. The default is {@ code false}. * * @ return whether to proxy or not to proxy the class * / boolean proxyTargetClass () default false;}

We can see that @ EnableAspectJAutoProxy (proxyTargetClass = false) is no stranger to this, just turning on the Spring AOP function.

Let's focus on @ Import (RetryConfiguration.class) @ Import is equivalent to registering this Bean.

Let's see what this RetryConfiguration is:

It is an AbstractPointcutAdvisor, it has a pointcut and an advice. We know that in the process of IOC, the Bean will be filtered by Pointcut according to the PointcutAdvisor class, and then the corresponding AOP proxy class will be generated, and advice will be used to enhance the processing.

Look at the initialization of RetryConfiguration:

@ PostConstruct public void init () {Set

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report