日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区

您的位置:首頁技術(shù)文章
文章詳情頁

SpringRetry重試框架的具體使用

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

spring retry主要實現(xiàn)了重試和熔斷。

不適合重試的場景:

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

適合重試的場景:

遠程調(diào)用超時、網(wǎng)絡突然中斷等可以重試。

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

一、環(huán)境搭建

加入SpringRetry依賴,SpringRetry使用AOP實現(xiàn),所以也需要加入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中可以指定監(jiān)聽、回退策略、重試策略等 只需要正常new RetryTemplate()即可使用2.2 RetryListener

RetryListener指定了當執(zhí)行過程中出現(xiàn)錯誤時的回調(diào)

org.springframework.retry.RetryListener

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

配置之后在RetryTemplate中指定

2.3 回退策略2.3.1 FixedBackOffPolicy

當出現(xiàn)錯誤時延遲多少時間繼續(xù)調(diào)用

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

配置之后在RetryTemplate中指定

2.3.2 ExponentialBackOffPolicy

當出現(xiàn)錯誤時第一次按照指定延遲時間延遲后按照指數(shù)進行延遲

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

配置之后在RetryTemplate中指定

2.4 重試策略

重試策略主要指定出現(xiàn)錯誤時重試次數(shù)

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

配置之后在RetryTemplate中指定

2.5 RetryCallback

RetryCallback為retryTemplate.execute時執(zhí)行的回調(diào)

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

SpringRetry重試框架的具體使用

2.6 核心使用

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

指定回退策略為ExponentialBackOffPolicy 指定重試策略為SimpleRetryPolicy 指定監(jiān)聽器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);*/// 指數(shù)回退(秒),第一次回退1s,第二次回退2sExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();exponentialBackOffPolicy.setInitialInterval(1000L);exponentialBackOffPolicy.setMultiplier(2);retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);// 重試策略SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();retryPolicy.setMaxAttempts(5);retryTemplate.setRetryPolicy(retryPolicy);// 設置監(jiān)聽器,open和close分別在啟動和結(jié)束時執(zhí)行一次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 -> {// 業(yè)務代碼// ....// 模擬拋出異常++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執(zhí)行18:27:20.649 - http-nio-8888-exec-1 - onError18:27:21.658 - http-nio-8888-exec-1 - retryTemplate.execute執(zhí)行18:27:21.658 - http-nio-8888-exec-1 - onError18:27:23.670 - http-nio-8888-exec-1 - retryTemplate.execute執(zhí)行18:27:23.670 - http-nio-8888-exec-1 - onError18:27:27.679 - http-nio-8888-exec-1 - retryTemplate.execute執(zhí)行18:27:27.679 - http-nio-8888-exec-1 - onError18:27:35.681 - http-nio-8888-exec-1 - retryTemplate.execute執(zhí)行18:27:35.681 - http-nio-8888-exec-1 - onError18:27:35.681 - http-nio-8888-exec-1 - close

三、EnableRetry

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

import org.springframework.retry.annotation.Retryable;public interface RetryService { /** * 重試方法調(diào)用 */ @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('方法調(diào)用..');throw new RuntimeException('手工異常'); }}

controller中注入service

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

將會默認重試

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

四、Retryable

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

Retryable注解參數(shù)

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

@Backoff 注解 重試補償策略

不設置參數(shù)時,默認使用FixedBackOffPolicy(指定等待時間),重試等待1000ms 設置delay,使用FixedBackOffPolicy(指定等待設置delay和maxDealy時,重試等待在這兩個值之間均態(tài)分布) 設置delay、maxDealy、multiplier,使用 ExponentialBackOffPolicy(指數(shù)級重試間隔的實現(xiàn)),multiplier即指定延遲倍數(shù),比如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;}

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

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

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

監(jiān)聽方法,在配置類中進行配置

/** * 注解調(diào)用 */@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繼續(xù)執(zhí)行后續(xù)調(diào)用 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);} };}

調(diào)用服務

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

調(diào)用結(jié)果

SpringRetry重試框架的具體使用

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

標簽: Spring
相關(guān)文章:
日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区
久久国产精品99国产| 欧美日韩在线精品一区二区三区激情综合| 日本va欧美va瓶| 亚洲精品伊人| 亚洲欧美在线专区| 一区二区三区网站| 色婷婷成人网| 日本精品在线播放| 石原莉奈在线亚洲二区| 久久亚洲国产精品一区二区| 玖玖玖国产精品| 四虎成人精品一区二区免费网站| 水蜜桃久久夜色精品一区的特点| 一区二区三区四区在线观看国产日韩| 日韩精品高清不卡| 国产亚洲欧美日韩在线观看一区二区| 欧美亚洲三级| 国产精品一区二区99| 久久精品国产久精国产爱| 丰满少妇一区| 99精品视频在线| 亚洲欧美久久| 国产日韩欧美中文在线| 精品国产精品国产偷麻豆| av综合电影网站| 精品一区免费| 日本不卡中文字幕| 精品国产精品久久一区免费式| 伊人网在线播放| 日韩亚洲在线| 18国产精品| 伊人久久av| 久色成人在线| 另类综合日韩欧美亚洲| 欧美日韩国产一区二区三区不卡| 亚洲一区二区三区四区五区午夜| 97久久超碰| 日韩欧美午夜| 热久久免费视频| 久久国产精品美女| 亚洲天堂久久| 91欧美精品| 中文无码日韩欧| 国产精品资源| 日本在线精品| 97久久超碰| 蜜桃一区二区三区在线| 香蕉久久国产| 免费在线观看一区| 久久精品免费一区二区三区| 亚洲精品护士| 九色porny丨国产首页在线| 免播放器亚洲一区| 国产精品久久久久av蜜臀| 欧洲亚洲一区二区三区| 婷婷精品在线| 亚洲性色av| 91精品国产自产在线丝袜啪| 色婷婷久久久| 国产欧美一区二区精品久久久| 成人免费网站www网站高清| 老牛国产精品一区的观看方式| 久久麻豆视频| 免费成人在线视频观看| 日韩.com| 国产亚洲一区| 香蕉久久久久久久av网站| yellow在线观看网址| 亚洲精品国产精品粉嫩| av高清不卡| 国产三级精品三级在线观看国产| 欧美日韩高清| 国产中文在线播放| 欧美日韩亚洲一区二区三区在线| 欧美成人亚洲| 国产一区二区三区日韩精品| 亚洲精品大全| 欧美综合另类| 精品国产aⅴ| 日本在线成人| 日韩视频不卡| 国产精品久久久久蜜臀| 欧美亚洲人成在线| 国产午夜精品一区二区三区欧美| 国产一区三区在线播放| 日韩av中文字幕一区二区| 一区二区视频欧美| 欧美aa在线观看| 麻豆精品一区二区综合av| 日韩高清成人在线| 男女男精品视频网| 午夜精品免费| 成人精品天堂一区二区三区| 国产一区福利| 你懂的国产精品永久在线| 日本va欧美va瓶| 日韩中文字幕一区二区三区| 久久五月天小说| 国产成人在线中文字幕| 欧美一区免费| 日本精品国产| 涩涩涩久久久成人精品| 视频一区免费在线观看| 免费国产自久久久久三四区久久 | 精品香蕉视频| 日韩成人精品一区二区三区| 亚洲欧美日韩精品一区二区 | 精品视频国内| 国产精品白丝av嫩草影院| 日韩精品亚洲专区| 综合一区在线| 五月亚洲婷婷 | re久久精品视频| 亚洲国内欧美| 国产主播一区| 欧美/亚洲一区| 日韩一区二区在线免费| 日韩av二区| 日韩欧美1区| 日韩毛片视频| 久久三级视频| 亚洲一级高清| 女同性一区二区三区人了人一 | 久久久国产精品一区二区中文| 国产一区二区三区久久| 精品网站999| 国产成人a视频高清在线观看| 精品国产欧美| 日韩欧美精品综合| 国产精品av久久久久久麻豆网| 国产99在线| 亚洲香蕉网站| 日韩一级不卡| 日韩精品免费一区二区夜夜嗨 | 97精品中文字幕| 神马午夜在线视频| 国产精品99免费看| 视频在线观看国产精品| 日韩福利在线观看| 久久99影视| 亚洲三级欧美| 婷婷综合亚洲| 亚洲欧美日韩国产一区二区| 麻豆成人在线| 91精品在线免费视频| 国产极品模特精品一二| 精品视频91| 亚洲福利一区| 亚洲18在线| 国产在线不卡一区二区三区| 久久久久蜜桃| 影音先锋久久精品| 国产欧美88| 成人片免费看| 视频在线在亚洲| 美女毛片一区二区三区四区最新中文字幕亚洲| 欧美91在线| 91精品99| 日韩高清不卡一区二区| 精品国产一区二区三区噜噜噜| 欧美亚洲日本精品| 国产精品女主播一区二区三区| 日本综合精品一区| 精品一区二区三区中文字幕| 欧美福利一区| 青青国产91久久久久久| 人在线成免费视频| 蜜臀av亚洲一区中文字幕| 国产精品网站在线看| 久久久成人网| 日本成人在线不卡视频| 伊伊综合在线| 亚洲理论在线| 高清一区二区| 91精品91| 国产精品久久久久久久久免费高清 | www在线观看黄色| 美女黄网久久| 欧美精品99| 九九综合在线| 国产欧美自拍| 亚洲黄色在线| 国产精品99久久免费观看| 久久一级电影| 久久av超碰| 99综合视频| 你懂的网址国产 欧美| 午夜一区在线| 亚洲午夜天堂| 日韩成人午夜精品| 91九色精品| 久久女人天堂| 亚洲乱码久久| 99精品综合| 国产精品免费精品自在线观看| 欧美91精品| 福利一区和二区| 日韩av资源网| 99国产精品视频免费观看一公开| 精品视频97|