Spring的异常重试框架Spring Retry简单配置讲解

相关api见:https://docs.spring.io/spring-retry/docs/api/current/org/springframework/retry/annotation/Retryable.html

/*
 * 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方式实现会比较宽松。

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值