相关api见:点击进入
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;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@documented
public @interface Retryable {
String interceptor() default "";
Class extends Throwable>[] value() default {};
Class extends Throwable>[] include() default {};
Class extends Throwable>[] exclude() default {};
String label() default "";
boolean stateful() default false;
int maxAttempts() default 3;
String maxAttemptsexpression() default "";
Backoff backoff() default @Backoff();
String exceptionexpression() default "";
}
下面就 Retryable的简单配置做一个讲解:
首先引入maven依赖:
org.springframework.retry spring-retryRELEASE
然后在方法上配置注解@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方式实现会比较宽松。
以上这篇Spring的异常重试框架Spring Retry简单配置操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。



