current position:Home>Springboot technology practice - springretry retry framework, java programmer interview written examination collection
Springboot technology practice - springretry retry framework, java programmer interview written examination collection
2022-01-27 01:40:44 【m0_ sixty-four million eight hundred and sixty-seven thousand e】
import com.codecoord.util.PrintUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryListener;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
@Configuration
public class RetryTemplateConfig {
/**
- Inject retryTemplate
*/
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
/// Fallback fixed time ( second )
/* FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(1000L);
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);*/
// Index fallback ( second ), First fallback 1s, Second fallback 2s
ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
exponentialBackOffPolicy.setInitialInterval(1000L);
exponentialBackOffPolicy.setMultiplier(2);
retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);
// Retrying strategy
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(5);
retryTemplate.setRetryPolicy(retryPolicy);
// Set listener ,open and close Execute once at startup and once at end
RetryListener[] listeners = {
new RetryListener() {
@Override
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
PrintUtil.print(“open”);
return true;
}
@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,
Throwable throwable) {
PrintUtil.print(“close”);
}
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback,
Throwable throwable) {
PrintUtil.print(“onError”);
}
}
};
retryTemplate.setListeners(listeners);
return retryTemplate;
}
}
- stay controller In the injection RetryTemplate Use , It can also be in service in
@RestController
public class SpringRetryController {
@Resource
private RetryTemplate retryTemplate;
private static int count = 0;
@RequestMapping("/retry")
public Object retry() {
try {
count = 0;
retryTemplate.execute((RetryCallback<Void, RuntimeException>) context -> {
// Business code
// …
// Mock exception
++count;
throw new RuntimeException(“ Throw an exception ”);
});
} catch (RuntimeException e) {
System.out.println(“Exception”);
}
return "retry = " + count;
}
}
- visit retry Interface , Then observe the log output
18:27:20.648 - http-nio-8888-exec-1 - open
18:27:20.649 - http-nio-8888-exec-1 - retryTemplate.execute perform
18:27:20.649 - http-nio-8888-exec-1 - onError
18:27:21.658 - http-nio-8888-exec-1 - retryTemplate.execute perform
18:27:21.658 - http-nio-8888-exec-1 - onError
18:27:23.670 - http-nio-8888-exec-1 - retryTemplate.execute perform
18:27:23.670 - http-nio-8888-exec-1 - onError
18:27:27.679 - http-nio-8888-exec-1 - retryTemplate.execute perform
18:27:27.679 - http-nio-8888-exec-1 - onError
18:27:35.681 - http-nio-8888-exec-1 - retryTemplate.execute perform
18:27:35.681 - http-nio-8888-exec-1 - onError
18:27:35.681 - http-nio-8888-exec-1 - close
================================================================================
-
@EnableRetry Turn on Retry , When specified on the class, the method will execute by default , Try again three times
-
Definition service, Turn on @EnableRetry Annotations and assignments @Retryable, Retry can refer to the following section
import org.springframework.retry.annotation.Retryable;
public interface RetryService {
/**
- Retry method call
*/
@Retryable
void retryServiceCall();
}
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.stereotype.Service;
@EnableRetry
@Service
public class RetryServiceImpl implements RetryService {
@Override
public void retryServiceCall() {
PrintUtil.print(“ Method call …”);
throw new RuntimeException(“ Manual exception ”);
}
}
- controller In the injection service
@RequestMapping("/retryAnnotation")
public Object retryAnnotation() {
retryService.retryServiceCall();
return “retryAnnotation”;
}
- Will retry by default
18:46:48.721 - http-nio-8888-exec-1 - Method call …
18:46:49.724 - http-nio-8888-exec-1 - Method call …
18:46:50.730 - http-nio-8888-exec-1 - Method call …
java.lang.RuntimeException: Manual exception
==============================================================================
-
Annotation on the method that needs to be retried
-
There are several properties
-
Retryable Annotation parameters
-
value: Specifies the exception that occurred to try again
-
include: and value equally , Default empty , When exclude Also empty , All exceptions are retried
-
exclude: Specifies that the exception is not retried , Default empty , When include Also empty , All exceptions are retried
-
maxAttemps: Retry count , Default 3
-
backoff: Retrial compensation mechanism , There is no default
-
@Backoff annotation Retry compensation strategy
-
When no parameters are set , By default FixedBackOffPolicy( Specify waiting time ), Try again and wait 1000ms
-
Set up delay, Use FixedBackOffPolicy( Specify wait settings delay and maxDealy when , Retry wait is evenly distributed between these two values )
-
Set up delay、maxDealy、multiplier, Use ExponentialBackOffPolicy( Implementation of exponential retry interval ),multiplier That is, specify the delay multiple , such as delay=5000L,multiplier=2, The first try is 5 second , The second time is 10 second , The third time is 20 second
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Retryable {
/**
-
Retry interceptor bean name to be applied for retryable method. Is mutually
-
exclusive with other attributes.
-
@return the retry interceptor bean name
*/
String interceptor() default “”;
/**
-
Exception types that are retryable. Synonym for includes(). Defaults to empty (and
-
if excludes is also empty all exceptions are retried).
-
@return exception types to retry
*/
Class<? extends Throwable>[] value() default {};
/**
-
Exception types that are retryable. Defaults to empty (and if excludes is also
-
empty all exceptions are retried).
-
@return exception types to retry
*/
Class<? extends Throwable>[] include() default {};
/**
-
Exception types that are not retryable. Defaults to empty (and if includes is also
-
empty all exceptions are retried).
-
If includes is empty but excludes is not, all not excluded exceptions are retried
-
@return exception types not to retry
*/
Class<? extends Throwable>[] exclude() default {};
/**
-
A unique label for statistics reporting. If not provided the caller may choose to
-
ignore it, or provide a default.
-
@return the label for the statistics
*/
String label() default “”;
/**
-
Flag to say that the retry is stateful: i.e. exceptions are re-thrown, but the
-
retry policy is applied with the same policy to subsequent invocations with the
-
same arguments. If false then retryable exceptions are not re-thrown.
-
@return true if retry is stateful, default false
*/
boolean stateful() default false;
/**
- @return the maximum number of attempts (including the first failure), defaults to 3
*/
int maxAttempts() default 3;
/**
-
@return an expression evaluated to the maximum number of attempts (including the first failure), defaults to 3
-
Overrides {@link #maxAttempts()}.
-
@date 1.2
*/
String maxAttemptsExpression() default “”;
/**
-
Specify the backoff properties for retrying this operation. The default is a
-
simple {@link Backoff} specification with no properties - see it’s documentation
-
for defaults.
-
@return a backoff specification
*/
Backoff backoff() default @Backoff();
/**
-
Specify an expression to be evaluated after the {@code SimpleRetryPolicy.canRetry()}
-
returns true - can be used to conditionally suppress the retry. Only invoked after
-
an exception is thrown. The root object for the evaluation is the last {@code Throwable}.
-
Other beans in the context can be referenced.
-
For example:
-
{@code “message.contains(‘you can retry this’)”}.
-
and
-
{@code “@someBean.shouldRetry(#root)”}.
-
@return the expression.
-
@date 1.2
*/
String exceptionExpression() default “”;
/**
-
Bean names of retry listeners to use instead of default ones defined in Spring context
-
@return retry listeners bean names
*/
String[] listeners() default {};
}
- Configure the corresponding number of retries on the method that needs to be retried 、 Retry the exception type of the exception 、 Set the fallback delay time 、 Retrying strategy 、 Method listener name
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Backoff {
/**
-
Synonym for {@link #delay()}.
-
@return the delay in milliseconds (default 1000)
*/
long value() default 1000;
/**
-
A canonical backoff period. Used as an initial value in the exponential case, and
-
as a minimum value in the uniform case.
-
@return the initial or canonical backoff period in milliseconds (default 1000)
*/
long delay() default 0;
/**
-
The maximimum wait (in milliseconds) between retries. If less than the
-
{@link #delay()} then the default of
-
{@value org.springframework.retry.backoff.ExponentialBackOffPolic
《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing
y#DEFAULT_MAX_INTERVAL}
-
is applied.
-
@return the maximum delay between retries (default 0 = ignored)
*/
long maxDelay() default 0;
/**
-
If positive, then used as a multiplier for generating the next delay for backoff.
-
@return a multiplier to use to calculate the next backoff delay (default 0 =
-
ignored)
*/
double multiplier() default 0;
/**
-
An expression evaluating to the canonical backoff period. Used as an initial value
-
in the exponential case, and as a minimum value in the uniform case. Overrides
-
{@link #delay()}.
-
@return the initial or canonical backoff period in milliseconds.
-
@date 1.2
*/
String delayExpression() default “”;
/**
-
An expression evaluating to the maximimum wait (in milliseconds) between retries.
-
If less than the {@link #delay()} then the default of
-
{@value org.springframework.retry.backoff.ExponentialBackOffPolicy#DEFAULT_MAX_INTERVAL}
-
is applied. Overrides {@link #maxDelay()}
-
@return the maximum delay between retries (default 0 = ignored)
-
@date 1.2
*/
String maxDelayExpression() default “”;
/**
-
Evaluates to a vaule used as a multiplier for generating the next delay for
-
backoff. Overrides {@link #multiplier()}.
-
@return a multiplier expression to use to calculate the next backoff delay (default
-
0 = ignored)
-
@date 1.2
*/
String multiplierExpression() default “”;
/**
-
In the exponential case ({@link #multiplier()} > 0) set this to true to have the
-
backoff delays randomized, so that the maximum delay is multiplier times the
-
previous delay and the distribution is uniform between the two values.
-
@return the flag to signal randomization is required (default false)
*/
boolean random() default false;
}
@Component
public class PlatformClassService {
@Retryable(
// Retry the exception type of the exception
value = {Exception.class},
// max retries
maxAttempts = 5,
// Set the fallback delay time
backoff = @Backoff(delay = 500),
// Configure callback method name
listeners = “retryListener”
)
public void call() {
System.out.println(“call…”);
throw new RuntimeException(“ Manual exception ”);
}
}
// Initial delay 2 second , And then acceptance 1.5 Double delay retry , Total retries 4
@Retryable(value = {Exception.class}, maxAttempts = 4, backoff = @Backoff(delay = 2000L, multiplier = 1.5))
- Monitoring methods , Configure in the configuration class
/**
- Annotation call
*/
copyright notice
author[m0_ sixty-four million eight hundred and sixty-seven thousand e],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270140431244.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command