spring-retry(4.interceptor包、annotation包)


这部分是retry包中最难部分了,主要是为了利用AOP机制,把任意声明为@Retryable的方法都变成可以可重试的。

interceptor包和annotation紧密相关。

annotation.png
  1. MethodArgumentsKeyGenerator接口:
Object getKey(Object[] item);

传入item通常为方法的参数,返回的Object为这些参数的唯一标识

  1. FixedKeyGenerator类:
    其简单实现,无论何种参数数组传入,都返回给定的Label值。
  2. MethodInvocationRecoverer接口:
    定义回复接口方法,具体声明如下:
T recover(Object[] args, Throwable cause);
  1. NewMethodArgumentsIdentifier接口:
    区别判断一组参数,之前是否执行过
  2. RetryOperationsInterceptor类
    由于Retry是利用AOP机制实现的,因而需要定义MethodInterceptor把我们声明的方法绑定到RetryTemplate的调用中去。
public Object invoke(final MethodInvocation invocation) throws Throwable {
        //先取到该方法调用的名字、
        String name;
        if (StringUtils.hasText(label)) {
            name = label;
        } else {
            name = invocation.getMethod().toGenericString();
        }
        final String label = name;
        //构造回调函数
        RetryCallback<Object, Throwable> retryCallback = new RetryCallback<Object, Throwable>() {

            public Object doWithRetry(RetryContext context) throws Exception {
                // 在上下文中登记Label
                context.setAttribute(RetryContext.NAME, label);
                // 多一重保险,判断是代理方法调用
                if (invocation instanceof ProxyMethodInvocation) {
                    try {
                        //实际利用动态方法调用,执行方法本身
                        return ((ProxyMethodInvocation) invocation).invocableClone().proceed();
                    }
                    catch (Exception e) {
                        // 捕捉后重新抛出
                        throw e;
                    }
                    catch (Error e) {
                        // 捕捉后重新抛出
                        throw e;
                    }
                    catch (Throwable e) {
                        // 其他错误,就是非法错误了。
                        throw new IllegalStateException(e);
                    }
                }
                else {
                    throw new IllegalStateException(
                            "MethodInvocation of the wrong type detected - this should not happen with Spring AOP, " +
                                    "so please raise an issue if you see this exception");
                }
            }

        };
        // 判断有无恢复方法,如果有,就构造一个恢复回调
        if (recoverer != null) {
            ItemRecovererCallback recoveryCallback = new ItemRecovererCallback(
                    invocation.getArguments(), recoverer);
            // 实际还是传入RetryTemplate执行方法调用
            return this.retryOperations.execute(retryCallback, recoveryCallback);
        }
        // 实际还是传入RetryTemplate执行方法调用
        return this.retryOperations.execute(retryCallback);

    }
  1. StatefulRetryOperationsInterceptor类:
    RetryOperationsInterceptor类是公用一个RetryTemplate的。而又状态的RetryOperationsInterceptor就必须每个实例都有自己的RetryTemplate,再配合RetryState决定是否需要抛出RollbackException了。其核心invoke方法如下:
public Object invoke(final MethodInvocation invocation) throws Throwable {

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Executing proxied method in stateful retry: "
                    + invocation.getStaticPart() + "("
                    + ObjectUtils.getIdentityHexString(invocation) + ")");
        }

        Object[] args = invocation.getArguments();
        Object defaultKey = Arrays.asList(args);
        if (args.length == 1) {
            defaultKey = args[0];
        }

        Object key = createKey(invocation, defaultKey);
        // 构造重试状态
        RetryState retryState = new DefaultRetryState(key,
                this.newMethodArgumentsIdentifier != null
                        && this.newMethodArgumentsIdentifier.isNew(args),
                this.rollbackClassifier);
        // 实际还是传入RetryTemplate执行方法调用
        Object result = this.retryOperations
                .execute(new MethodInvocationRetryCallback(invocation, label),
                        this.recoverer != null
                                ? new ItemRecovererCallback(args, this.recoverer) : null,
                        retryState);

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Exiting proxied method in stateful retry with result: ("
                    + result + ")");
        }

        return result;

    }
  1. RetryInterceptorBuilder类
    流式构造的工厂RetryInterceptor类。具体使用的例子如下:
 StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful() //构造有状态的Interceptor
        .maxAttempts(5).backOffOptions(1, 2, 10) // initialInterval, multiplier,
        .build();

这个工厂能生产3种不同的Interceptor,StatefulRetryInterceptor(有状态的),StatelessRetryInterceptor(无状态),CircuitBreakerInterceptor(有状态加熔断)。

  1. RecoverAnnotationRecoveryHandler<T>类:
    MethodInvocationRecoverer的实现,根据一个方法,查找对应@Recover注解方法,封装到Recovery处理之中,也就是@Retryable和@Recover的自动匹配过程。从构造器可以看出,保存了目标类和目标方法,然后进行解析。
// target为目标类,method为需要Revover的目标方法
public RecoverAnnotationRecoveryHandler(Object target, Method method) {
        this.target = target;
        init(target, method);
    }

其核心的init方法代码如下:

private void init(Object target, Method method) {
        final Map<Class<? extends Throwable>, Method> types = new HashMap<Class<? extends Throwable>, Method>();
        //保存传入的方法作为备份方法
        final Method failingMethod = method;
        //调用ReflectionUtils反射工具,查找符合条件目标方法
        ReflectionUtils.doWithMethods(failingMethod.getDeclaringClass(),
                new MethodCallback() {
                    @Override
                    // 声明回调函数,每个符合条件的目标方法,都会登记到types和methods中
                    public void doWith(Method method) throws IllegalArgumentException,
                            IllegalAccessException {
                        //查找@Recover接口
                        Recover recover = AnnotationUtils.findAnnotation(method,
                                Recover.class);
                        if (recover != null
                                && failingMethod.getReturnType().isAssignableFrom(
                                        method.getReturnType())) {
                            Class<?>[] parameterTypes = method.getParameterTypes();
                            //判断找到的方法和目标方法参数,异常是否一致
                            if (parameterTypes.length > 0
                                    && Throwable.class
                                            .isAssignableFrom(parameterTypes[0])) {
                                @SuppressWarnings("unchecked")
                                Class<? extends Throwable> type = (Class<? extends Throwable>) parameterTypes[0];
                                //登记下这个revover方法的参数
                                types.put(type, method);
                                methods.put(method, new SimpleMetadata(
                                        parameterTypes.length, type));
                            } else {
                                //找不到,就给配置个默认值
                                classifier.setDefaultValue(method);
                                methods.put(method, new SimpleMetadata(
                                        parameterTypes.length, null));
                            }
                        }
                    }
                });
        classifier.setTypeMap(types);
    }
  1. AnnotationAwareRetryOperationsInterceptor类:
    注解解析器,查找工程中@Retryable方法,并生成RetryOperationsInterceptor的类。

  2. RetryConfiguration类:
    @EnableRetry引入的配置类,内部封装AnnotationClassOrMethodPointcut,AnnotationClassOrMethodFilter,AnnotationMethodsResolver三个Aop工具类。通过反射查找到目标方法,并应用aop给方法加料(生成proxy对象),从而实现把普通方法变成可重试方法。


最后总结一下

虽然看过去东西很多,实际上除了概念理解外,真正需要掌握的核心只有:

  • 三个注解:@EnableRetry,@Retryable,@Recover;
  • 两个策略:补偿策略,重试策略。(具体策略较多,但也比较容易理解);
  • 一个模板:RetryTemplate。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,227评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,755评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,899评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,257评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,617评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,757评论 1 221
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,982评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,715评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,454评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,666评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,148评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,512评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,156评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,112评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,896评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,809评论 2 279
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,691评论 2 272

推荐阅读更多精彩内容