SpringBoot技术实践-SpringRetry重试框架

一、环境树立

  1. 加入SpringRetry依靠,SpringRetry运用AOP结束,所以也需求加入AOP包
<!-- SpringRetry -->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</depejavaapi中文在线看ndency>
<dependency&gthttp 302;
<groupId>org.spr业务性作业是什么意思ingframework</groupId>
<artifactId>spring-aspects</artifactId>
</de业务文书pendency>
  1. 官方文档
    • www.baeldung.cjava初学om/spring-retr…

二、RetryTemplate

2.1 RetryTemplate

  1. RetryTemplate封装HTTP了Retry底子操作
    • org.springframework.retry.support.RetryTemplate
  2. RetryTemplate中可以指定监听、回退战略、java难学吗重试战略等
  3. 只需求正常new RetryTemplate()即可运用

2.2 RetryListener

  1. RetryListener指定了当实施过程中呈现过错时的回javaapi中文在线看
    • org.springframewohttp://www.baidu.comrk.retry.RetryListener
package org.springframework.retry;
public interface RetryListener {
/**
* 使命开始实施时调用,只调用一次
*/
<T, E extends Throwable> boolean open(Retrapp下载yContext context, RetryC业务员allback<T, E> callback);
/**
* 使命实施结束https和http的差异时(包含重试)调用,只调用一次
*/
<T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable);
/**
* 呈现过错时回调
*/
<T, E extends Thro接口crc过错计数wable> void onError(RetryContext context, RetryCall接口文档back<T, E> callback, Throwable throwable);
}
  1. 装备之后在RetryTemplate中指定

2.3HTTP 回退战略

2.3.1 FixedBackOffPolicy

  1. 当出业务文书现过错时推迟多少时刻继续调用
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(1000L);
retryTem接口测验面试题plate.setBackOf接口crc过错计数fPolicy(fixedBackOffPolicy);
  1. 装备之后在RetryTempl业务性作业ate中指定

2.3.2 Expone业务性作业是什么意思ntihttp代理alBackOffPolicy

  1. 当呈现过错时第一次按照指定推迟时刻推迟后按照指数进行推迟
// 指数回退(秒),第一次回退1s,接口类型第2次回退2s,第三次4秒,第四次8秒
ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
exponejava言语ntialBackOffPolicy.setInitialInterval(1000L);
expoappearnentialBackOffPolicy.set接口crc过错计数Multiplier(2);
retryTemplat业务所e.setBackOffPolicy(exponentialBackOffPolicy);
  1. 装备之后在RetryTemplate中指定

2.4 重试战略

  1. 重试战略首要指定呈现过错时重试次数
// 重试APP战略
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(5);
retryTemplate.setRhttpwatchetryPolicy(retryPolicy);
  1. 装备之后在RetryTemplate中指定

2.5 RetryCallback

  1. RetryCallback为retryTemplate.execute时实施的回调
    • public final <Tappreciate, E exapproachtends Throwable> T execute(RetryCallback<T, E&g业务的四个特性t; retryC业务所是干什么的allback) throws E

SpringBoot技术实践-SpringRetry重试结构

2.6 中心运用

  1. 可以运用RetryTempl业务所是干什么的ate结束简单运用
  2. 装备retryTemplate
    • 指定回退战略为ExponentialBhttp://www.baidu.comackOffPolicy
    • 指定重试战略为SimpleRetryPolicy
    • 指定监听器RetryListener
import com.codecoord.util.PrintUtil;
import org.springframework.context.annotation.Bean;
import or业务性作业是什么意思g.springframework.context.annotation.Cohttps和http的差异nfiguration;
import org.springframework.retry.RetryCallback;
impor业务t org.springframework.retry.RetryContext;
impojava初学rt org.spri业务ngframework.retry.RetryListener;
im业务所port org.springframework.retry.backoff.Exponapp是什么意思entialBapplicationackOffPolicy;
import org.springfra接口的界说mework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
@Configuration
public class RetryTemplateConfig {
/**
* 注入retryTempla接口和抽象类的差异te
*/
@Bean
public RetryTemplate retryTemplate() {application
RetryTemplaappreciatete retryTemplate =httpclient new RetryTemplate();
/// 回退固定时刻(秒)
/* FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(1000L)http 404;
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);*/
// 指数回退(秒),第一次回退1s,第2次接口文档回退2s
ExponentialBackOffPolicyappearance exponentialappearanceBahttp://www.baidu.comckOffPolicy = new Exponentia接口和抽象类的差异lBackOffPolicy();
exponentialBackOffPolicy.setInitialInterval(1000L);
eappreciatexponentialBackOffPolicy.setMultiplier(2);
retryjavascriptTemplate.setBackOffPolicy(exponentialBackOffPolicy);
// 重试战略
SimpleRet业务所ryPolicy retryPolicy = new SimpleRetryPolicy();
retrjava言语yPolicy.setMaxAttempts(5);
retryTemplate.setRetryPolicy(retryPolicy);
// 设置监听器,open和close分别在启动和结束时实施一次
RetryListener[] listeners = {
new RetryListener() {
@Override
public接口文档 <T, E extends T接口文档hrowable> boolean open(RetryContext contextjava模拟器, RetryCallbacjava言语k<T, E&javaapi中文在线看gt; callback) {
PrintUtil.接口是什么print("open");
return true;
}
@Override
public <T, E extends Throwable> void close(RetryContext context, Ret接口是什么ryCallback<T, E> callback,
Throwable throwable) {
PrintUtil.print("close");
}
@Override
public <T, E extend接口s Throwable> voi接口的界说d onErrojavaapi中文在线看r(R接口卡etryCoappstorentext context, RappointmentetryCallback<T, E> callback,
Throwable throwable) {
PrintUtil.print("onError");
}
}
};
retryTemplate.setLi业务性作业是什么意思steners(listeners);
return retrhttps和http的差异yTemplate;
}
}
  1. 在controller中注入RetryTemplate运用,也可以是在servijava面试题ce中
@RestChttp://www.baidu.comontroller
public class SpringRethttp 404ryController {
@Resource
priva接口的界说te RetryTemplate retryTempjava怎么读late;
private static int count = 0;
@RequestMapping("/retry")
public Object retry() {
try {
count = 0;
retryTemplate.execute((RetryCallback<Voiapp是什么意思d, RuntimeExcepHTTPtion>) co接口是什么ntext -> {
// 业务代码
// ....
// 仿照抛出异常
++count;
throw new RuntimeException("抛出异常");
});
} catch (RuntimeExcappeareption e)接口文档 {
System.outhttpclient.println("Exception");
}
return "retry = " + count;
}
}
  1. 拜访retry接口,然后调查日志输出
18:27:20.648 - http-nio-8888-exec-1 - open
18:27:20.649 - http-nio-888app是什么意思8-exec-1 - retryT接口的效果em接口测验plathttpwatche.execute实施
18:27:javaee20.649 - http-nio-8888-exec-1 - onError
18:27:21.658 - http-接口nio-8888-ex业务的四个特性ec-1 - retryTemplate.execute实施
18:27:21.658 - http-nio-8888-exec-1 - onError
18:27:2java面试题3.670 - http-nio-888接口和抽象类的差异8-exec-1 - retryT接口测验面试题emplate.execute实施
18:27:23.670 - http-nio-8888-exec-1 - onError
18:27:27.679 - http-nio-8888业务性作业是什么意思-exec-1 - retryTemplathttps和http的差异e.execute实施
18:27:27.679 - http-nio-8888-exec-1 - onError
18:27:35.681 - http-nio-8888java模拟器-exec-1 - retryTemplate.execute实施
18:27:35.681 - http-nio-8888-e接口是什么xec-1 - onError
18:27:35业务员.681 - http-nio-8888-exec-1 - close

三、EnableRetry

  1. @EnableRetrjava作业培训班y打开重试,在类上指定的时分办法将默许实施,重试三次
  2. 界说serv业务员ice,打开@EnableRetry注解和指定@Retryable,重试可以参看后面接口的界说一节
import org.springframework.retry.annotation.Retryable;
public interface RetryService {
/**
* 重试办法调用
*/
@Retryable
void retryServiceCall();
}
import org.springframework.retry.annotation.EnableRetry;
impo业务员rt org.springframework.st接口和抽象类的差异ereotype.Service;
@EnableRetry
@Service
public clahttps和http的差异ss RetryServiceImpl implements RetrySehttp://www.baidu.comrvice {
@Override
public void retryServiceCall() {
PrintUtil.print("办法调用..");
throw new RuntimeException("手艺异常");
}
}
  1. controller中注入service
@Requesjava模拟器tMapping("/retr业务文书yAnnotation")
public Objeapplicationc接口测验t retryAnnotation()javascript {
retryService.retryServiceCall();
return "retryAnnotation";
}
  1. 将会默许重试
18:46:48httpclient.721 - http-nio-8888-exec-1 - 办法调用..
18:46:49.724 - http-nappointmentio-8javaapi中文在线看888-exec-1 - 办法调用..
18:46:50.730 - http-nio-8888-exec-1 - 办法调用..
java.lan业务g.Runtimhttp 500eException: 手艺HTTP异常接口crc过错计数

四、Retryable

  1. 用于http://www.baidu.com需求重试的办法上的注解
  2. 有以下几个特javascript
    • Retryaappreciateble注解参数
      • value:指定产生的异常进行重试
      • include:和value一样,默许空,当exclude也为空时,全部异常都重试
      • exclude:指定异常不重试,默许空,当include也为空时,全部异常都重试
      • maxAttemps:重试次数,默许3
      • backoffapp是什么意思:重试补偿机制,默许没接口crc过错计数
    • @Backoff 注解 重试补偿java模拟器战略
      • 不设置参数时,默许运用FixedBackOffPolicy(指定等候时刻)接口文档,重试等候1000ms
      • 设置delay,运用FixedBackOffPolicy(指定等候设置delay和maxDealy时,重试等候在这两个值之间均态散布)
      • 设置delay、maxDealy、multiplier,运用 ExponentialBackOffPolicyapproach(指数级重试间隔的结束),multiplier即指定推迟倍数,比方delay=5000L,multiplhttp协议ier=2,则第一次重试为5秒,第2次为10秒,第三次为20秒
@Target({ ElementType.METHOD, Elhttp 404ementType.TYPE })
@Retentjavascription(RetentionPolicy.RUNTIME)
@Documenthttp 500ed
public @interfajavaapi中文在线看ce Retryable {
/**
* Retry interceptor bean name to be aapplepplied for retryable method. Is mutually
* exclusive with other attribut业务所es.
* @return thejava言语 retry interceptor bean name
*/
Strappreciateing interceptor() default "";
/**
* Exceptapp是什么意思ion t接口ypes that are retryable. Synon接口和抽象类的差异ym for includes(). Defaults to empty业务的四个特性 (and
* if excludes is also empty all ejava初学xceptions are retriapproached).
* @return exception types to retry
*Java/
Class<? extends Th接口测验面试题rowable>[业务性作业是什么意思] value() default {};
/java言语**
* E业务所是干什么的xception types that are retryable. Defaults to emptapplicationy (and ifhttps和http的差异 excludes is also
* empty all exceptions are ret接口测验ried).
* @return exception types to rhttpclientetry
*/
Class<? extends Throwabjavaeele>[] include() defauhttps和http的差异lt {};
/**
* Exception types that ar业务文书e not retryable. Defau接口lts to empty (and if includes is also
* empty all exceptions are retried).
* I业务f includes is empty but excludes is not, all nothttp 500 excluded exceptions are retried
* @return exception types not to retry
*appearance/
Class<? extends Throwable>[] exclude() default {};
/**
* A unique label for statistics reporti业务所ng. If not provided the callHTTPer may choose to
* ignor业务的四个特性e it, or provide a default.
*
* @return thhttpcliente label for the statistics
*/
String label() default ""接口的效果;
/**
* Flag t接口是什么o say that the rJavaetry is stateful: i.e. exceptions are re-thrown, but the
* retry policy is applijavaapi中文在线看ed with the same policy to subsequent invocations with the
* same argume接口的界说nts. If false then retryable exceptions are not re-thrown.
* @return true if retry is stateful, default false
*/
boolean stateful() default false;
/**
* @return the maxjava难学吗imum number of attempts (including接口的界说 the first failure), defaults to 3
*app下载/
injavaapi中文在线看t maxAttempts() default 3;
/**
* @r接口和抽象类的差异etujava作业培训班rn an exprejava难学吗ssion evaluaAPPted to the maximum number of attempts (java怎么读i接口测验ncluding the first failure), defaults to 3
* Overrides {@link #maxAttempts()}.
* @date 1.2
*/
String maxAttemptsExpression() default "";
/**
* Spehttpwatchcify the backoff properties for retrying this operation. The default is a
* simple {@link Backoff} specification with no properties - see it's documentation
* for default业务s.
* @return a backoff specification
*/
Backoff backof业务所是干什么的f() default @Backoff()java面试题;
/**
* S业务的四个特性pecify an expression to be evaluated after the {@code SimpleRetryPolicy.canRetry()}
* returns true - can be used to conditionalappearancely sup接口测验面试题press the retry. Only invoked after
* an exceptiapp是什么意思on is thrown. The root object for the evaluation is the last {@code Throwable}.
* Other beans in the context can be referenced.
* For example:
* <pre class=code>
*  {@code "message.contains('you can retry this')"}.
* </pre>
* and
* &接口和抽象类的差异lt;pre class=httpclientcode>
*  {@code "@somehttpclientBean.shouldjava作业培训班Retry(#root)"}.
* </pre>
* @return the expression.
* @date 1.2
*/
String exceptionExpression() default "";
/**
* Bean names of retry listeners to use instead o业务所是干什么的f default ones defined in Spring context
* @return retjavaapi中文在线看ry listeners bean names
*/
String[]接口类型 listeners() default {};
}
@Target(ElementThttp 404ype.TYPE)
@Retentappointmention(RetentionPolicy.RUNTIME)
@Documented
public @interface Backofhttp://192.168.1.1登录f {
/**
* Synonym for {@link #delay()}.
*
* @return the delay in milliseconds (接口default 1000)
*/
long value() default 1000;
/**
* A canonical backoff period. Usedhttps和http的差异 as an initiaappearl value in the exponential case, and
* as a minimum value in th业务阻隔等级e uniform case.
* @reapp是什么意思turn the initial or canonical backoff period in milliseconds (default 1000)
*/
long delay() default 0;
/**
*接口测验 The maximimum wait (in millisecon业务ds) between rethttp 302ries. If less than the
* {@link #delapp是什么意思ay()} then the default oappointmentf
* {@value org.springframework.retry.backoff.ExponentialBackOffPolicy#DEFAULT_MAX_INTERVAL}
* is applied.
*
* @return the maximujava初学m delay between retries (default 0 = ignored)
*/
long maxhttp://192.168.1.1登录Delay() defauappstorelt 0;
/**
* If positive, then u业务文书简报的期数指的是sed as a multiplie接口的效果r for generating the next delay for backoff.
*
* @return a multiplier to use to接口测验面试题 calculate the接口文档 next backoff delay (def业务阻隔等级ault 0 =java模拟器
* ignored)
*/
double multiplier() default 0;
/**
* An expression evaluating to the canonical backoff period. U业务文书简报的期数指的是sed as an initial valueappstore
* in the exponential case, and as a minimum value in the uniform case. Overrid接口和抽象类的差异es
* {@link #delay()}.
* @return the initial or canonical backoff period in milliseconds.
* @date 1.2
*/
String delay业务性作业Expression() default "";
/**
* An exphttp代理ression evaluating to the maximimum wait (in milliseconds) between rappstoreetrijava初学es.
*http://192.168.1.1登录 If less than the {@link #delay()} then the default of
* {@v业务alue org.springframework.java怎么读retjava模拟器ry.backoff.ExponentialBackOffPolicy#DEFAULT_MAX_INTERVAL}
* is applied. Oappointmentverrides {@link #maxDelay()}
*
* @return the maximum delay between retries (业务文书default 0 = ignored)
* @date 1.2
*/
String maxDelayExpression() default "Java";
/**
* Evaluates to a vaule usjavascripted as a multiplier for generating the next delay for
* backoff. Overrides {@link #multiplier()}.
*
* @return a multiplier expre业务性作业ssion to use to calc接口卡ulate the next backoff delay (default
* 0 = ignored)
* @date 1.2
*/
String multiplierExpression() default "";
/**
* In the exponential case ({@link #multiplier()} &gt; 0) set this to true to have the
* backoff delays randomized, so that the maximum delay is muappstoreltiplier times the
* previous del接口的界说ay and the distribution is uniform业务所 between the two values.
*
* @return the flag to signal randomization is required (default false)
*/
booleanapp是什么意思 random() default false;
}
  1. 在需求重试的http协议办法上装备对应的重试次数、重试异常的异常类型、设置回退推迟时刻、重试战略、办法监听称谓
@Component
puapp下载blic class PlatformClassService {
@Retryhttpwatchable(
// 重试异常的异常类型
value = {Exception.class},
// 最大重试次数
maxAtt接口crc过错计数empt接口crc过错计数s = 5,
// 设置业务文书回退推迟时刻
backoff = @Backoff(delay = 500),
// 装备回调办法称谓
listeners = "retryListener"
)
public void call() {
System.业务的四个特性out.println("call...");
throw new RuntimeException("手艺异常");http://192.168.1.1登录
}
}
// 初始推迟2秒,然后之后验收1.5倍推迟重试,总重试次数4
@Retryable(value = {Exception.appearanceclass}, maxAttempts = 4, backoff = @Backoff(delay = 2000L, muljavaeetiplier = 1.5))
  1. 监听办法,在装备类中进行装备
/**
* 注解调用
*/
@Be业务所an
public Retry业务所Listener re接口tryListener() {
return new RetryListener() {
@Overridhttp 404e
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
System.out.println业务的四个特性("open context =appreciate " + context + ", calappstorelback = " + callback);
// 回来true继续实施后续调用
return true;
}
@Override
p接口是什么ublic <T, E extends Throwable&app下载gt; void cljava难学吗ose(Rjava初学etryContext context, RetryCallback<T, E> callback,
Throwable throwable) {
System.out.println("close context = " + context + ", caAPPllback业务文书简报的期数指的是 = " + callba业务性作业ck);
}
@Override
public <T, E ejava怎么读xtends Throwable> void onError(RetryContext context,业务员 Rejavaapi中文在线看tryCallback<T, E> callback,http://192.168.1.1登录
Throwaapp是什么意思ble throwable) {
System.out.println("onErrojava言语r context = " + context + ", callback = " + callback);
}
};
}
  1. 调用服务
@RestController
public class SpringRetryCon接口和抽象类的差异troller {
@Resource
private Platfor业务mClassService platformhttp 404Clashttp 302sService;
@RequestMapping("/接口和抽象类的差异retryPlatformCall")
public Object retryPlatformCall() {
try {
platformClass接口是什么Service.ca接口和抽象类的差异ll();
} catch (Exception e) {
return "尝试调用失利";
}
return "retryPlatformCall";
}
}
  1. 调用成果

SpringBoot技术实践-SpringRetry重试结构

发表评论

提供最优质的资源集合

立即查看 了解详情