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

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

Spring的異常重試框架Spring Retry簡單配置操作

瀏覽:82日期:2023-08-13 15:40:25

相關api見:點擊進入

/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.retry.annotation; import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target; /** * Annotation for a method invocation that is retryable. * * @author Dave Syer * @author Artem Bilan * @author Gary Russell * @since 1.1 * */@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). * @return exception types 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()}. * @since 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. * @since 1.2 */String exceptionExpression() default ''; }

下面就 Retryable的簡單配置做一個講解:

首先引入maven依賴:

<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> <version>RELEASE</version> </dependency>

然后在方法上配置注解@Retryable

@Override@SuppressWarnings('Duplicates')@Retryable(value = {RemoteAccessException.class}, maxAttempts = 3, backoff = @Backoff(delay = 3000l, multiplier = 0))public boolean customSendText(String openid, String content) throws RemoteAccessException { String replyString = '{n' + ''touser':' + openid + ',n' + ''msgtype':'text',n' + ''text':n' + '{n' + ''content':' + content + 'n' + '}n' + '}'; try { logger.info('wx:customSend=request:{}', replyString.toString()); HttpsClient httpClient = HttpsClient.getAsyncHttpClient(); String url = Constant.WX_CUSTOM_SEND; String token = wxAccessokenService.getAccessToken(); url = url.replace('ACCESS_TOKEN', token); logger.info('wx:customSend=url:{}', url); String string = httpClient.doPost(url, replyString); logger.info('wx:customSend=response:{}', string); if (StringUtils.isEmpty(string)) throw new RemoteAccessException('發(fā)送消息異常'); JSONObject jsonTexts = (JSONObject) JSON.parse(string); if (jsonTexts.get('errcode') != null) { String errcode = jsonTexts.get('errcode').toString(); if (errcode == null) {throw new RemoteAccessException('發(fā)送消息異常'); } if (Integer.parseInt(errcode) == 0) {return true; } else {throw new RemoteAccessException('發(fā)送消息異常'); } } else { throw new RemoteAccessException('發(fā)送消息異常'); } } catch (Exception e) { logger.error('wz:customSend:{}', ExceptionUtils.getStackTrace(e)); throw new RemoteAccessException('發(fā)送消息異常'); }}

注解內容介紹:

@Retryable注解

被注解的方法發(fā)生異常時會重試

value:指定發(fā)生的異常進行重試

include:和value一樣,默認空,當exclude也為空時,所有異常都重試

exclude:指定異常不重試,默認空,當include也為空時,所有異常都重試

maxAttemps:重試次數(shù),默認3

backoff:重試補償機制,默認沒有

@Backoff注解

delay:指定延遲后重試

multiplier:指定延遲的倍數(shù),比如delay=5000l,multiplier=2時,第一次重試為5秒后,第二次為10秒,第三次為20秒

注意:

1、使用了@Retryable的方法不能在本類被調用,不然重試機制不會生效。也就是要標記為@Service,然后在其它類使用@Autowired注入或者@Bean去實例才能生效。

2、使用了@Retryable的方法里面不能使用try...catch包裹,要在發(fā)放上拋出異常,不然不會觸發(fā)。

3、在重試期間這個方法是同步的,如果使用類似Spring Cloud這種框架的熔斷機制時,可以結合重試機制來重試后返回結果。

4、Spring Retry不僅能注入方式去實現(xiàn),還可以通過API的方式實現(xiàn),類似熔斷處理的機制就基于API方式實現(xiàn)會比較寬松。

以上這篇Spring的異常重試框架Spring Retry簡單配置操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標簽: Spring
相關文章:
主站蜘蛛池模板: 杭州标识标牌|文化墙|展厅|导视|户内外广告|发光字|灯箱|铭阳制作公司 - 杭州标识标牌|文化墙|展厅|导视|户内外广告|发光字|灯箱|铭阳制作公司 | 酒瓶_酒杯_玻璃瓶生产厂家_徐州明政玻璃制品有限公司 | 蔬菜清洗机_环速洗菜机_异物去除清洗机_蔬菜清洗机_商用洗菜机 - 环速科技有限公司 | 据信,上课带着跳 D 体验-别样的课堂刺激感受引发网友热议 | 轴承振动测量仪电箱-轴承测振动仪器-测试仪厂家-杭州居易电气 | 分轨 | 上传文件,即刻分离人声和伴奏 | 交变/复合盐雾试验箱-高低温冲击试验箱_安奈设备产品供应杭州/江苏南京/安徽马鞍山合肥等全国各地 | 大流量卧式砂磨机_强力分散机_双行星双动力混合机_同心双轴搅拌机-莱州市龙跃化工机械有限公司 | X光检测仪_食品金属异物检测机_X射线检测设备_微现检测 | 陶氏道康宁消泡剂_瓦克消泡剂_蓝星_海明斯德谦_广百进口消泡剂 | 济南电缆桥架|山东桥架-济南航丰实业有限公司 | 硅胶制品-硅橡胶制品-东莞硅胶制品厂家-广东帝博科技有限公司 | 吲哚菁绿衍生物-酶底物法大肠菌群检测试剂-北京和信同通科技发展有限公司 | 冷凝锅炉_燃气锅炉_工业燃气锅炉改造厂家-北京科诺锅炉 | 插针变压器-家用电器变压器-工业空调变压器-CD型电抗器-余姚市中驰电器有限公司 | 不锈钢监控杆_监控立杆厂家-廊坊耀星光电科技有限公司 | 东莞市天进机械有限公司-钉箱机-粘箱机-糊箱机-打钉机认准东莞天进机械-厂家直供更放心! | 理化生实验室设备,吊装实验室设备,顶装实验室设备,实验室成套设备厂家,校园功能室设备,智慧书法教室方案 - 东莞市惠森教学设备有限公司 | nalgene洗瓶,nalgene量筒,nalgene窄口瓶,nalgene放水口大瓶,浙江省nalgene代理-杭州雷琪实验器材有限公司 | 奥运星-汽车性能网评-提供个性化汽车资讯 | 定制液氮罐_小型气相液氮罐_自增压液氮罐_班德液氮罐厂家 | 高防护蠕动泵-多通道灌装系统-高防护蠕动泵-www.bjhuiyufluid.com慧宇伟业(北京)流体设备有限公司 | 硅胶制品-硅橡胶制品-东莞硅胶制品厂家-广东帝博科技有限公司 | 螺杆泵_中成泵业| hc22_hc22价格_hc22哈氏合金—东锜特殊钢 | 螺旋丝杆升降机-SWL蜗轮-滚珠丝杆升降机厂家-山东明泰传动机械有限公司 | 污泥烘干机-低温干化机-工业污泥烘干设备厂家-焦作市真节能环保设备科技有限公司 | 化妆品加工厂-化妆品加工-化妆品代加工-面膜加工-广东欧泉生化科技有限公司 | 广州食堂承包_广州团餐配送_广州堂食餐饮服务公司 - 旺记餐饮 | 嘉兴恒升声级计-湖南衡仪声级计-杭州爱华多功能声级计-上海邦沃仪器设备有限公司 | 安全,主动,被动,柔性,山体滑坡,sns,钢丝绳,边坡,防护网,护栏网,围栏,栏杆,栅栏,厂家 - 护栏网防护网生产厂家 | 好物生环保网、环保论坛 - 环保人的学习交流平台 | 双菱电缆-广州电缆厂_广州电缆厂有限公司 | 钢绞线万能材料试验机-全自动恒应力两用机-混凝土恒应力压力试验机-北京科达京威科技发展有限公司 | 涡轮流量计_LWGY智能气体液体电池供电计量表-金湖凯铭仪表有限公司 | 编织人生 - 权威手工编织网站,编织爱好者学习毛衣编织的门户网站,织毛衣就上编织人生网-编织人生 | 全自动贴标机-套标机-工业热风机-不干胶贴标机-上海厚冉机械 | 圣才学习网-考研考证学习平台,提供万种考研考证电子书、题库、视频课程等考试资料 | Brotu | 关注AI,Web3.0,VR/AR,GPT,元宇宙区块链数字产业 | 北京翻译公司-专业合同翻译-医学标书翻译收费标准-慕迪灵 | 礼仪庆典公司,礼仪策划公司,庆典公司,演出公司,演艺公司,年会酒会,生日寿宴,动工仪式,开工仪式,奠基典礼,商务会议,竣工落成,乔迁揭牌,签约启动-东莞市开门红文化传媒有限公司 |