前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >聊聊spring cloud的consulRetryInterceptor

聊聊spring cloud的consulRetryInterceptor

原创
作者头像
code4it
修改2019-07-29 12:17:01
8790
修改2019-07-29 12:17:01
举报
文章被收录于专栏:码匠的流水账

本文主要研究一下spring cloud的consulRetryInterceptor

consulRetryInterceptor

spring-cloud-consul-core-2.1.2.RELEASE-sources.jar!/org/springframework/cloud/consul/ConsulAutoConfiguration.java

代码语言:javascript
复制
@Configuration
@EnableConfigurationProperties
@ConditionalOnConsulEnabled
public class ConsulAutoConfiguration {
    //......
​
    @ConditionalOnClass({ Retryable.class, Aspect.class, AopAutoConfiguration.class })
    @Configuration
    @EnableRetry(proxyTargetClass = true)
    @Import(AopAutoConfiguration.class)
    @EnableConfigurationProperties(RetryProperties.class)
    protected static class RetryConfiguration {
​
        @Bean(name = "consulRetryInterceptor")
        @ConditionalOnMissingBean(name = "consulRetryInterceptor")
        public RetryOperationsInterceptor consulRetryInterceptor(
                RetryProperties properties) {
            return RetryInterceptorBuilder.stateless()
                    .backOffOptions(properties.getInitialInterval(),
                            properties.getMultiplier(), properties.getMaxInterval())
                    .maxAttempts(properties.getMaxAttempts()).build();
        }
​
    }
​
    //......
}
  • RetryConfiguration注册了consulRetryInterceptor,它基于RetryProperties创建了RetryOperationsInterceptor

RetryProperties

spring-cloud-consul-core-2.1.2.RELEASE-sources.jar!/org/springframework/cloud/consul/RetryProperties.java

代码语言:javascript
复制
@ConfigurationProperties("spring.cloud.consul.retry")
public class RetryProperties {
​
    /** Initial retry interval in milliseconds. */
    private long initialInterval = 1000;
​
    /** Multiplier for next interval. */
    private double multiplier = 1.1;
​
    /** Maximum interval for backoff. */
    private long maxInterval = 2000;
​
    /** Maximum number of attempts. */
    private int maxAttempts = 6;
​
    public RetryProperties() {
    }
​
    public long getInitialInterval() {
        return this.initialInterval;
    }
​
    public void setInitialInterval(long initialInterval) {
        this.initialInterval = initialInterval;
    }
​
    public double getMultiplier() {
        return this.multiplier;
    }
​
    public void setMultiplier(double multiplier) {
        this.multiplier = multiplier;
    }
​
    public long getMaxInterval() {
        return this.maxInterval;
    }
​
    public void setMaxInterval(long maxInterval) {
        this.maxInterval = maxInterval;
    }
​
    public int getMaxAttempts() {
        return this.maxAttempts;
    }
​
    public void setMaxAttempts(int maxAttempts) {
        this.maxAttempts = maxAttempts;
    }
​
    @Override
    public String toString() {
        return new ToStringCreator(this).append("initialInterval", this.initialInterval)
                .append("multiplier", this.multiplier)
                .append("maxInterval", this.maxInterval)
                .append("maxAttempts", this.maxAttempts).toString();
    }
​
}
  • RetryProperties定义了initialInterval、multiplier、maxInterval、maxAttempts属性

AopAutoConfiguration

spring-boot-autoconfigure-2.1.6.RELEASE-sources.jar!/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java

代码语言:javascript
复制
@Configuration
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class, AnnotatedElement.class })
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {
​
    @Configuration
    @EnableAspectJAutoProxy(proxyTargetClass = false)
    @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false",
            matchIfMissing = false)
    public static class JdkDynamicAutoProxyConfiguration {
​
    }
​
    @Configuration
    @EnableAspectJAutoProxy(proxyTargetClass = true)
    @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
            matchIfMissing = true)
    public static class CglibAutoProxyConfiguration {
​
    }
​
}
  • AopAutoConfiguration根据spring.aop.proxy-target-class来注入不同的代理方式,默认是cglib代理

RetryOperationsInterceptor

spring-retry-1.2.4.RELEASE-sources.jar!/org/springframework/retry/interceptor/RetryOperationsInterceptor.java

代码语言:javascript
复制
public class RetryOperationsInterceptor implements MethodInterceptor {
​
    private RetryOperations retryOperations = new RetryTemplate();
​
    private MethodInvocationRecoverer<?> recoverer;
​
    private String label;
​
    public void setLabel(String label) {
        this.label = label;
    }
​
    public void setRetryOperations(RetryOperations retryTemplate) {
        Assert.notNull(retryTemplate, "'retryOperations' cannot be null.");
        this.retryOperations = retryTemplate;
    }
​
    public void setRecoverer(MethodInvocationRecoverer<?> recoverer) {
        this.recoverer = recoverer;
    }
​
    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 {
                
                context.setAttribute(RetryContext.NAME, label);
​
                /*
                 * If we don't copy the invocation carefully it won't keep a reference to
                 * the other interceptors in the chain. We don't have a choice here but to
                 * specialise to ReflectiveMethodInvocation (but how often would another
                 * implementation come along?).
                 */
                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);
            return this.retryOperations.execute(retryCallback, recoveryCallback);
        }
​
        return this.retryOperations.execute(retryCallback);
​
    }
​
    /**
     * @author Dave Syer
     *
     */
    private static final class ItemRecovererCallback implements RecoveryCallback<Object> {
​
        private final Object[] args;
​
        private final MethodInvocationRecoverer<?> recoverer;
​
        /**
         * @param args the item that failed.
         */
        private ItemRecovererCallback(Object[] args, MethodInvocationRecoverer<?> recoverer) {
            this.args = Arrays.asList(args).toArray();
            this.recoverer = recoverer;
        }
​
        public Object recover(RetryContext context) {
            return recoverer.recover(args, context.getLastThrowable());
        }
​
    }
​
}
  • RetryOperationsInterceptor实现了aopalliance的MethodInterceptor;它将invocation包装为retryCallback,然后使用RetryTemplate实现重试

小结

  • RetryConfiguration注册了consulRetryInterceptor,它基于RetryProperties创建了RetryOperationsInterceptor
  • RetryProperties定义了initialInterval、multiplier、maxInterval、maxAttempts属性
  • RetryOperationsInterceptor实现了aopalliance的MethodInterceptor;它将invocation包装为retryCallback,然后使用RetryTemplate实现重试

doc

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • consulRetryInterceptor
  • RetryProperties
  • AopAutoConfiguration
  • RetryOperationsInterceptor
  • 小结
  • doc
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档