spring项目中使用AOP实现熔断

package com.awna.platform.support.client.sale.aspect;

import com.netflix.hystrix.*;
import com.qunar.awna.support.client.sale.common.util.ClientResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class HystrixCommandAspect {

    private static final String COMMAND_KEY = "ticket_special_command";
    private static final String GROUP_KEY = COMMAND_KEY + "_group";
    private static final String THREAD_POOL_KEY = COMMAND_KEY + "_threadPool";
    private static final int TIMEOUT = 1000;
    private static final int POOL_CORE_SIZE = 150;
    private static final int MAX_QUEUE_SIZE = 100;
    private static final int REJECT_QUEUE_SIZE = 100;

    @Pointcut("execution(* com.awna.platform.support.client.sale.service.business.*(..))")
    public void hystrixPointcut(){}
    @Around("hystrixPointcut()")
    public Object runCommand(final ProceedingJoinPoint pJoinPoint){
        return warpWithHystrixCommand(pJoinPoint).execute();
    }

    private HystrixCommand<Object> warpWithHystrixCommand(final ProceedingJoinPoint pJoinPoint){
        String method = pJoinPoint.getSignature().getName();
        return new HystrixCommand<Object>(setter(method)){
            @Override
            protected Object run() {
                try {
                    return pJoinPoint.proceed();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                }
                return null;
            }

            @Override
            protected Object getFallback() {
                return new ClientResult(-1,"hystrix error");
            }
        };
    }

    private HystrixCommand.Setter setter(String method){
        return HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(GROUP_KEY))
                .andCommandKey(HystrixCommandKey.Factory.asKey(COMMAND_KEY))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(THREAD_POOL_KEY))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(TIMEOUT))
                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(POOL_CORE_SIZE)
                        .withMaxQueueSize(MAX_QUEUE_SIZE).withQueueSizeRejectionThreshold(REJECT_QUEUE_SIZE));
    }
}

想了解更多java相关技术,请关注公众号“JavaEE那些事”

扫描下面二维码,更多技术资料等你来拿
这里写图片描述

猜你喜欢

转载自blog.csdn.net/forwujinwei/article/details/79728440