J2EE之巅

 

Spring AOP on Annotation

1 The annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface NeedToRetry {
    Class<?>[] recoverableExceptions();
    int retryTime();
    int intervalIncrementalFactor() default 0;
    long retryInterval() default 0L;
}

2 The Aspect
@Aspect
public class InvokingRetryInterceptor {
    private static Logger log = Logger.getLogger(InvokingRetryInterceptor.class);
    private boolean isNeedToRetry(Throwable t,Class<?>[] recoverableExceptions){
        String exceptionName= t.getClass().getName();
        for (Class<?> exp:recoverableExceptions){            
            if (exp.isInstance(t)){
                return true;
            }
        }
        log.warn("The exception doesn't need recover!"+exceptionName);
        return false;
    }

    private long getRetryInterval(int tryTimes,long interval,int incrementalFactor){
        return interval+(tryTimes*incrementalFactor);
    }
    
    @Around(value="@annotation(amazon.internal.dropship.common.NeedToRetry)&&@annotation(retryParam)",argNames="retryParam")
    public Object process(ProceedingJoinPoint pjp,NeedToRetry retryParam ) throws Throwable{
        boolean isNeedTry=true;
        int count=0;
        Throwable fault;            
        Class<?>[] recoverableExceptions=retryParam.recoverableExceptions();
        int retryTime=retryParam.retryTime();
        long retryInterval=retryParam.retryInterval();
        int incrementalFactor=retryParam.intervalIncrementalFactor();
        do{
            try{                
                return pjp.proceed();            
            }catch(Throwable t){
                fault=t;
                if (!isNeedToRetry(t,recoverableExceptions)){
                    break;
                }
                Thread.sleep(getRetryInterval(retryTime,retryInterval,incrementalFactor));
            }
            count++;
        }while(count<(retryTime+1));
        throw fault;
        
    }
}

posted on 2011-06-07 11:34 超越巅峰 阅读(4392) 评论(3)  编辑  收藏 所属分类: Java EE

评论

# re: Spring AOP on Annotation[未登录] 2011-06-07 16:24 quaff

用spring aop有个限制就是被aop拦截的方法被this对象的另一个方法调用会绕过aop  回复  更多评论   

# re: Spring AOP on Annotation 2011-06-15 13:42 懒人助手

有些图片会更好,http://www.lrtool.net  回复  更多评论   

# re: Spring AOP on Annotation[未登录] 2013-05-17 14:06 cc

more examples:
@Around("execution(public * amazon.internal.dropship.core.external.services.*Gateway*.*(..)) && (!execution(public * amazon.internal.dropship.core.external.services.*GatewayMemory*.*(..)))")

About cast AOP proxy:
if(AopUtils.isJdkDynamicProxy(gateway)){
impl = (SCSGatewayImpl) ((Advised)gateway).getTargetSource().getTarget();
}else{
impl = (SCSGatewayImpl) gateway;
}  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(12)

随笔分类(54)

随笔档案(59)

文章分类(2)

文章档案(1)

相册

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜