Spring的异常重试框架Spring Retry简单配置操作
作者:狂丰 发布时间:2023-11-25 18:27:35
标签:Spring,重试,Retry
相关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)
@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).
* @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("发送消息异常");
JSONObject jsonTexts = (JSONObject) JSON.parse(string);
if (jsonTexts.get("errcode") != null) {
String errcode = jsonTexts.get("errcode").toString();
if (errcode == null) {
throw new RemoteAccessException("发送消息异常");
}
if (Integer.parseInt(errcode) == 0) {
return true;
} else {
throw new RemoteAccessException("发送消息异常");
}
} else {
throw new RemoteAccessException("发送消息异常");
}
} catch (Exception e) {
logger.error("wz:customSend:{}", ExceptionUtils.getStackTrace(e));
throw new RemoteAccessException("发送消息异常");
}
}
注解内容介绍:
@Retryable注解
被注解的方法发生异常时会重试
value:指定发生的异常进行重试
include:和value一样,默认空,当exclude也为空时,所有异常都重试
exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试
maxAttemps:重试次数,默认3
backoff:重试补偿机制,默认没有
@Backoff注解
delay:指定延迟后重试
multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒
注意:
1、使用了@Retryable的方法不能在本类被调用,不然重试机制不会生效。也就是要标记为@Service,然后在其它类使用@Autowired注入或者@Bean去实例才能生效。
2、使用了@Retryable的方法里面不能使用try...catch包裹,要在发放上抛出异常,不然不会触发。
3、在重试期间这个方法是同步的,如果使用类似Spring Cloud这种框架的熔断机制时,可以结合重试机制来重试后返回结果。
4、Spring Retry不仅能注入方式去实现,还可以通过API的方式实现,类似熔断处理的机制就基于API方式实现会比较宽松。
来源:https://blog.csdn.net/fz13768884254/article/details/83176459


猜你喜欢
- 前言本文给你提供在Spring Boot 应用程序中编写好的单元测试的机制,并且深入技术细节。我们将带你学习如何以可测试的方式创建Sprin
- 本文实例讲述了Android实现音量调节的方法。分享给大家供大家参考。具体如下:main.xml布局文件:<?xml version=
- FilterInputStream 介绍FilterInputStream 的作用是用来“封装其它的输入流,并为它们提供额外的功能”。它的常
- 本文实例总结了Android横竖屏切换相关技巧。分享给大家供大家参考,具体如下:一、禁止横竖屏切换Android横竖屏切换在手机开发中比较常
- 本文实例展示了C#基于TimeSpan实现倒计时效果的方法,比较实用的功能,对于初学者来说有一定的学习参考价值。具体实现方法如下:示例代码如
- 本文主要介绍了Spring Security OAuth2 实现登录互踢的示例代码,分享给大家,具体如下:背景说明一个账号只能一处登录,类似
- 一、背景在上一篇文章中,我们使用Seata整合了SpringBoot,在这篇文章中我们使用Seata整合SpringCloud。同时有了上一
- 新手练手必备~密码账户为:先创建账户类:package cn.Atm;/*** @author 偶my耶*/import java.io.*
- 背景今天学习Springboot,但是用的apache-maven 3.0 ,导入springboot1.5.19 ,Maven项目老是爆红
- 1.场景线程池使用DiscardOldestPolicy拒绝策略,阻塞队列使用ArrayBlockingQueue,发现在某些情形下对于得到
- 序言:事件:此web项目的功能及其简单,就是有客户端来访问redis序列号服务时发送jison报文,项目已经在测试环境成功运行2周了,具体的
- HashMap的keySet()方法比较简单,作用是获取HashMap中的key的集合。虽然这个方法十分简单,似乎没有什么可供分析的,但真正
- 高斯模糊高斯模糊(英语:Gaussian Blur),也叫高斯平滑,是在Adobe Photoshop、GIMP以及Paint.NET等图像
- 在使用JDBC的时候,数据库据连接是非常宝贵的资源。为了复用这些资源,可以将连接保存在一个队列中。当需要的时候可以从队列中取出未使用的连接。
- 本文实例为大家分享了Java多线程实现复制文件的具体代码,供大家参考,具体内容如下/** * 实现文件复制功能 * 多线
- Java IO BufferedInputStream概要:BufferedInputStream是缓冲输入流,继承于Filte
- 现在看我文章的多数是一些老Android了,相信每个人使用起LayoutInflater都是家常便饭,信手拈来。但即使是这样,我仍然觉得这个
- Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使
- 前言值类型和引用类型,是c#比较基础,也必须掌握的知识点,但是也不是那么轻易就能掌握,今天跟着老胡一起来看看吧。 典型类型首先我们
- 本文实例讲述了Android编程实现的首页左右滑动切换功能。分享给大家供大家参考,具体如下:很多软件会选择左右滑动的主界面,实现方式也很多,