我是Hystrix的新手。我正在尝试将其与Spring AOP一起使用。以下详细说明了我要实现的目标。

有一个“ ServiceClass”,其中注入了一些RestClient类。我正在使用Spring。现在,我想将Hystrix与Spring AOP一起使用,以便可以同步或异步进行ServiceClass对RestClient的方法调用。

到目前为止,我所做的如下。

创建了一个扩展了HystrixCommand的类“ MyCommand”,该类实现了MethodInterceptor

在其中实现了方法“ execute(MethodInvocation m,字符串模式)”,如下所示:

                      protected Object execute(MethodInvocation m, String mode){
                      this.mode = mode;
                      this.method = m;
                      return execute();}


(覆盖方法)中的“调用”

                       public Object invoke(MethodInvocation m) throws throwable{
                         try{
                              execute(m,"Sync");
                         } catch(Exception e){
                             e.printStackTrace();
                         }
                        }


该“ MyCommand”在spring-config文件中被设置为“ ServiceClass”的AOP拦截器。

现在,问题是;在我的“主”应用程序中,当我从ClassPathXmlApplicationContext检索“ ServiceClass”并调用一种方法时,它可以正常工作。但是,如果我尝试调用“ ServiceClass”的两个方法,则会抛出以下异常:

              *java.lang.IllegalStateException: This instance can only be executed once. Please instantiate a new instance.*


程式码片段:

              ServiceClass srvc = (ServiceClass) ctx.getBean("proxy");
              srvc.getRequest();
              srvc.postRequest();


我花了将近三天的时间来找出导致此异常的原因和解决方案,但没有任何好处。请帮助我解决这个问题。我想念什么?

一如既往,
提前致谢

最佳答案

HystrixCommand对象只能使用一次,因为它在执行后包含有用的状态信息,可用于进一步处理。例如,如果要在run()调用超时后进行特殊处理,可以执行以下操作:

public class MyHystrixCommand extends HystrixCommand<Object> { ... }

MyHystrixCommand command = new MyHystrixCommand();

command.execute();

if(command.isResponseTimedOut()){
    //do post processing
}


如果您可以多次调用execute(),特别是从多个线程中调用时(如果您有多个REST端点的使用者),您将无法知道在查询命令状态时哪个调用超时了。 。

10-02 10:12