【问题标题】:How to use HystrixCommand inside a spring AOP class如何在 Spring AOP 类中使用 HystrixCommand
【发布时间】:2018-05-06 06:22:48
【问题描述】:

在我当前的项目中,我需要使用 Hystrix 进行请求回退处理(主要是请求超时回退)。我测试了一个简单的案例,将@HystrixCommand 注释放在一个弹簧休息控制器方法之上,如下所示:

@RestController
public class xxxxxx {

    @RequestMapping(value = "xxxxxxx")
        @HystrixCommand(fallbackMethod="fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "2000"),
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })
    public String xxxxxx(@RequestParam(value = "xxxx", required = true) String xxxx) {
        ....
        return json.toString();
    }

}

这很好用。超时在 2 秒后触发,并进入我预定义的回退方法。现在问题来了:控制器上的方法太多,项目中的控制器也很多。按方法复制和粘贴@HystrixCommand方法不是一个好主意,我需要通过spring aop来实现它。 然后我写了如下内容:

@Aspect
@Configuration
public class TimeoutMonitor {

    @Pointcut("execution(xxxxxxxx)")
    public void excuteService() {}

    @Around("excuteService()")
    @HystrixCommand(fallbackMethod="fallback", commandProperties = {
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "2000"),
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })
    public Object monitor(ProceedingJoinPoint pjp){
        try {
            Object output = pjp.proceed();
            return output;
        }catch(Throwable e) {
            return null;
        }
    }

    @HystrixCommand
    public String fallback(ProceedingJoinPoint pjp) {
        JSONObject json = new JSONObject();
        json.put("message", "request timeout");
        return json.toString();
    }
}

而且它不起作用......永远无法达到后备方法

在调试的过程中,我确定逻辑流程经过了excuteService()->monitor()->matched方法的流程,已经过了2秒,但是一直没有到达fallback方法。我研究过这个问题,发现@HystrixCommand也是AOP实现的。我想将一个 aop 放入另一个是导致此问题的原因,但不幸的是我想不出解决它的方法。

如果有人可以提供解决方案,我将不胜感激。非 aop 实现的方案也是可以接受的,但绝对不允许在每个方法上面复制粘贴@HystrixCommand。

【问题讨论】:

    标签: java spring spring-boot spring-aop hystrix


    【解决方案1】:

    由于这个问题还没有回复,所以我把自己的临时解决办法放在这里。

    首先,在spring aop中使用hystrix还是不行,所以唯一的努力是减少对控制器的影响。 Hystrix 允许在 springboot application.properties 文件中设置默认超时,如下所示:

    hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=3000
    hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=3000
    

    通过这种方式,需要放在每个方法上方的注释减少到只有一行:

    @HystrixCommand(fallbackMethod="fallback")
    

    这在这些方面仍然不够简洁:

    • 需要为每个方法复制/粘贴此注解

    • 需要在每个使用 hystrix 的地方复制/粘贴回退方法

    • 对于hystrix fallback方法本身,参数类型和数量需要与hystrix标记方法完全相同。目前,我在每个控制器中为此使用了几种称为“回退”的重载方法

    虽然还没有我想象的那么简洁,但目前我能想到的就这么多了。一旦找到更好的解决方案,将执行更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多