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那些事”

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值