电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

SpringRetry重試框架的具體使用

瀏覽:2日期:2023-06-29 15:44:46
目錄一、環境搭建二、RetryTemplate2.1 RetryTemplate2.2 RetryListener2.3 回退策略2.3.1 FixedBackOffPolicy2.3.2 ExponentialBackOffPolicy2.4 重試策略2.5 RetryCallback2.6 核心使用三、EnableRetry四、Retryable

spring retry主要實現了重試和熔斷。

不適合重試的場景:

參數校驗不合法、寫操作等(要考慮寫是否冪等)都不適合重試。

適合重試的場景:

遠程調用超時、網絡突然中斷等可以重試。

在spring retry中可以指定需要重試的異常類型,并設置每次重試的間隔以及如果重試失敗是繼續重試還是熔斷(停止重試)。

一、環境搭建

加入SpringRetry依賴,SpringRetry使用AOP實現,所以也需要加入AOP包

<!-- SpringRetry --><dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId></dependency><dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId></dependency>

官方文檔

二、RetryTemplate2.1 RetryTemplate RetryTemplate封裝了Retry基本操作 org.springframework.retry.support.RetryTemplate RetryTemplate中可以指定監聽、回退策略、重試策略等 只需要正常new RetryTemplate()即可使用2.2 RetryListener

RetryListener指定了當執行過程中出現錯誤時的回調

org.springframework.retry.RetryListener

package org.springframework.retry;public interface RetryListener { /** * 任務開始執行時調用,只調用一次 */ <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback); /** * 任務執行結束時(包含重試)調用,只調用一次 */ <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable); /** * 出現錯誤時回調 */ <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable);}

配置之后在RetryTemplate中指定

2.3 回退策略2.3.1 FixedBackOffPolicy

當出現錯誤時延遲多少時間繼續調用

FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();fixedBackOffPolicy.setBackOffPeriod(1000L);retryTemplate.setBackOffPolicy(fixedBackOffPolicy);

配置之后在RetryTemplate中指定

2.3.2 ExponentialBackOffPolicy

當出現錯誤時第一次按照指定延遲時間延遲后按照指數進行延遲

// 指數回退(秒),第一次回退1s,第二次回退2s,第三次4秒,第四次8秒ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();exponentialBackOffPolicy.setInitialInterval(1000L);exponentialBackOffPolicy.setMultiplier(2);retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);

配置之后在RetryTemplate中指定

2.4 重試策略

重試策略主要指定出現錯誤時重試次數

// 重試策略SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();retryPolicy.setMaxAttempts(5);retryTemplate.setRetryPolicy(retryPolicy);

配置之后在RetryTemplate中指定

2.5 RetryCallback

RetryCallback為retryTemplate.execute時執行的回調

public final <T, E extends Throwable> T execute(RetryCallback<T, E> retryCallback) throws E

SpringRetry重試框架的具體使用

2.6 核心使用

可以使用RetryTemplate完成簡單使用配置retryTemplate

指定回退策略為ExponentialBackOffPolicy 指定重試策略為SimpleRetryPolicy 指定監聽器RetryListener

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;@Configurationpublic class RetryTemplateConfig { /** * 注入retryTemplate */ @Bean public RetryTemplate retryTemplate() {RetryTemplate retryTemplate = new RetryTemplate();/// 回退固定時間(秒) /* FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();fixedBackOffPolicy.setBackOffPeriod(1000L);retryTemplate.setBackOffPolicy(fixedBackOffPolicy);*/// 指數回退(秒),第一次回退1s,第二次回退2sExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();exponentialBackOffPolicy.setInitialInterval(1000L);exponentialBackOffPolicy.setMultiplier(2);retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);// 重試策略SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();retryPolicy.setMaxAttempts(5);retryTemplate.setRetryPolicy(retryPolicy);// 設置監聽器,open和close分別在啟動和結束時執行一次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; }}

在controller中注入RetryTemplate使用,也可以是在service中

@RestControllerpublic 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 -> {// 業務代碼// ....// 模擬拋出異常++count;throw new RuntimeException('拋出異常'); });} catch (RuntimeException e) { System.out.println('Exception');}return 'retry = ' + count; }}

訪問retry接口,然后觀察日志輸出

18:27:20.648 - http-nio-8888-exec-1 - open18:27:20.649 - http-nio-8888-exec-1 - retryTemplate.execute執行18:27:20.649 - http-nio-8888-exec-1 - onError18:27:21.658 - http-nio-8888-exec-1 - retryTemplate.execute執行18:27:21.658 - http-nio-8888-exec-1 - onError18:27:23.670 - http-nio-8888-exec-1 - retryTemplate.execute執行18:27:23.670 - http-nio-8888-exec-1 - onError18:27:27.679 - http-nio-8888-exec-1 - retryTemplate.execute執行18:27:27.679 - http-nio-8888-exec-1 - onError18:27:35.681 - http-nio-8888-exec-1 - retryTemplate.execute執行18:27:35.681 - http-nio-8888-exec-1 - onError18:27:35.681 - http-nio-8888-exec-1 - close

三、EnableRetry

@EnableRetry開啟重試,在類上指定的時候方法將默認執行,重試三次定義service,開啟@EnableRetry注解和指定@Retryable,重試可以參考后面一節

import org.springframework.retry.annotation.Retryable;public interface RetryService { /** * 重試方法調用 */ @Retryable void retryServiceCall();}

import org.springframework.retry.annotation.EnableRetry;import org.springframework.stereotype.Service;@EnableRetry@Servicepublic class RetryServiceImpl implements RetryService { @Override public void retryServiceCall() {PrintUtil.print('方法調用..');throw new RuntimeException('手工異常'); }}

controller中注入service

@RequestMapping('/retryAnnotation')public Object retryAnnotation() { retryService.retryServiceCall(); return 'retryAnnotation';}

將會默認重試

18:46:48.721 - http-nio-8888-exec-1 - 方法調用..18:46:49.724 - http-nio-8888-exec-1 - 方法調用..18:46:50.730 - http-nio-8888-exec-1 - 方法調用..java.lang.RuntimeException: 手工異常

四、Retryable

用于需要重試的方法上的注解有以下幾個屬性

Retryable注解參數

value:指定發生的異常進行重試 include:和value一樣,默認空,當exclude也為空時,所有異常都重試 exclude:指定異常不重試,默認空,當include也為空時,所有異常都重試 maxAttemps:重試次數,默認3 backoff:重試補償機制,默認沒有

@Backoff 注解 重試補償策略

不設置參數時,默認使用FixedBackOffPolicy(指定等待時間),重試等待1000ms 設置delay,使用FixedBackOffPolicy(指定等待設置delay和maxDealy時,重試等待在這兩個值之間均態分布) 設置delay、maxDealy、multiplier,使用 ExponentialBackOffPolicy(指數級重試間隔的實現),multiplier即指定延遲倍數,比如delay=5000L,multiplier=2,則第一次重試為5秒,第二次為10秒,第三次為20秒

@Target({ ElementType.METHOD, ElementType.TYPE })@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @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: * <pre class=code> * {@code 'message.contains(’you can retry this’)'}. * </pre> * and * <pre class=code> * {@code '@someBean.shouldRetry(#root)'}. * </pre> * @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 {};}

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @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.ExponentialBackOffPolicy#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()} &gt; 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;}

在需要重試的方法上配置對應的重試次數、重試異常的異常類型、設置回退延遲時間、重試策略、方法監聽名稱

@Componentpublic class PlatformClassService { @Retryable(// 重試異常的異常類型value = {Exception.class},// 最大重試次數maxAttempts = 5,// 設置回退延遲時間backoff = @Backoff(delay = 500),// 配置回調方法名稱listeners = 'retryListener' ) public void call() {System.out.println('call...');throw new RuntimeException('手工異常'); }}

// 初始延遲2秒,然后之后驗收1.5倍延遲重試,總重試次數4@Retryable(value = {Exception.class}, maxAttempts = 4, backoff = @Backoff(delay = 2000L, multiplier = 1.5))

監聽方法,在配置類中進行配置

/** * 注解調用 */@Beanpublic RetryListener retryListener() { return new RetryListener() {@Overridepublic <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) { System.out.println('open context = ' + context + ', callback = ' + callback); // 返回true繼續執行后續調用 return true;}@Overridepublic <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) { System.out.println('close context = ' + context + ', callback = ' + callback);}@Overridepublic <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) { System.out.println('onError context = ' + context + ', callback = ' + callback);} };}

調用服務

@RestControllerpublic class SpringRetryController { @Resource private PlatformClassService platformClassService;@RequestMapping('/retryPlatformCall') public Object retryPlatformCall() {try { platformClassService.call();} catch (Exception e) { return '嘗試調用失敗';}return 'retryPlatformCall'; }}

調用結果

SpringRetry重試框架的具體使用

到此這篇關于SpringRetry重試框架的具體使用的文章就介紹到這了,更多相關SpringRetry重試框架內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 德国GMN轴承,GMN角接触球轴承,GMN单向轴承,GMN油封,GMN非接触式密封 | 河南15年专业网站建设制作设计,做网站就找郑州启凡网络公司 | 直流电能表-充电桩电能表-导轨式电能表-智能电能表-浙江科为电气有限公司 | 众品家具网-家具品牌招商_家具代理加盟_家具门户的首选网络媒体。 | 上海律师事务所_上海刑事律师免费咨询平台-煊宏律师事务所 | 不锈钢电动球阀_气动高压闸阀_旋塞疏水调节阀_全立阀门-来自温州工业阀门巨头企业 | 欧盟ce检测认证_reach检测报告_第三方检测中心-深圳市威腾检验技术有限公司 | 定量包装机,颗粒定量包装机,粉剂定量包装机,背封颗粒包装机,定量灌装机-上海铸衡电子科技有限公司 | 衬氟旋塞阀-卡套旋塞阀-中升阀门首页| 申江储气罐厂家,储气罐批发价格,储气罐规格-上海申江压力容器有限公司(厂) | 网站优化公司_北京网站优化_抖音短视频代运营_抖音关键词seo优化排名-通则达网络 | ASA膜,ASA共挤料,篷布色母料-青岛未来化学有限公司 | 阻燃剂-氢氧化镁-氢氧化铝-沥青阻燃剂-合肥皖燃新材料 | 宁波普瑞思邻苯二甲酸盐检测仪,ROHS2.0检测设备,ROHS2.0测试仪厂家 | 山东石英砂过滤器,除氟过滤器「价格低」-淄博胜达水处理 | 旋振筛_不锈钢旋振筛_气旋筛_旋振筛厂家—新乡市大汉振动机械有限公司 | 铸铁平台,大理石平台专业生产厂家_河北-北重机械 | 正压密封性测试仪-静态发色仪-导丝头柔软性测试仪-济南恒品机电技术有限公司 | 水冷散热器_水冷电子散热器_大功率散热器_水冷板散热器厂家-河源市恒光辉散热器有限公司 | 流程管理|流程管理软件|企业流程管理|微宏科技-AlphaFlow_流程管理系统软件服务商 | 西门子代理商_西门子变频器总代理-翰粤百科 | 西安微信朋友圈广告投放_微信朋友圈推广_西安度娘网络科技有限公司 | 江苏全风,高压风机,全风环保风机,全风环形高压风机,防爆高压风机厂家-江苏全风环保科技有限公司(官网) | 干粉砂浆设备_干混砂浆生产线_腻子粉加工设备_石膏抹灰砂浆生产成套设备厂家_干粉混合设备_砂子烘干机--郑州铭将机械设备有限公司 | 北京模型公司-工业模型-地产模型-施工模型-北京渝峰时代沙盘模型制作公司 | 电缆接头_防水接头_电缆防水接头 - 乐清市新豪电气有限公司 | 电磁流量计厂家_涡街流量计厂家_热式气体流量计-青天伟业仪器仪表有限公司 | 江苏农村商业银行招聘网_2024江苏农商行考试指南_江苏农商行校园招聘 | 色油机-色母机-失重|称重式混料机-称重机-米重机-拌料机-[东莞同锐机械]精密计量科技制造商 | 金属软管_不锈钢金属软管_巩义市润达管道设备制造有限公司 | 北京模型公司-工业模型-地产模型-施工模型-北京渝峰时代沙盘模型制作公司 | 冷却塔降噪隔音_冷却塔噪声治理_冷却塔噪音处理厂家-广东康明冷却塔降噪厂家 | 四川职高信息网-初高中、大专、职业技术学校招生信息网 | 上海单片机培训|重庆曙海培训分支机构—CortexM3+uC/OS培训班,北京linux培训,Windows驱动开发培训|上海IC版图设计,西安linux培训,北京汽车电子EMC培训,ARM培训,MTK培训,Android培训 | 交联度测试仪-湿漏电流测试仪-双85恒温恒湿试验箱-常州市科迈实验仪器有限公司 | 喷播机厂家_二手喷播机租赁_水泥浆洒布机-河南青山绿水机电设备有限公司 | 粤丰硕水性环氧地坪漆-防静电自流平厂家-环保地坪涂料代理 | 钢丝绳探伤仪-钢丝绳检测仪-钢丝绳探伤设备-洛阳泰斯特探伤技术有限公司 | 新疆十佳旅行社_新疆旅游报价_新疆自驾跟团游-新疆中西部国际旅行社 | 标准光源箱|对色灯箱|色差仪|光泽度仪|涂层测厚仪_HRC大品牌生产厂家 | 天津次氯酸钠酸钙溶液-天津氢氧化钠厂家-天津市辅仁化工有限公司 |