【问题标题】:IllegalStateException with HystrixHystrix 的 IllegalStateException
【发布时间】:2015-04-02 13:25:17
【问题描述】:

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

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

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

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

在其中实现了一个方法“execute(MethodInvocation m, String mode),如下:

                      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.*

代码sn-p:

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

我花了将近三天的时间试图找出这个异常的原因和解决方案,但没有任何好处。请帮我解决这个问题。我错过了什么?

一如既往, 提前致谢

【问题讨论】:

  • 好的,看起来不能在 Hystrix 命令的同一个实例上多次调用 execute() (虽然不太清楚为什么)。所以修改了代码,每次都使用一个新的 Hystrix 命令实例。它有效。

标签: java spring-aop hystrix


【解决方案1】:

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

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

MyHystrixCommand command = new MyHystrixCommand();

command.execute();

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

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

【讨论】:

  • 是的,收到了,因此也发表了评论。
  • 是的,我看到了。我只是想说明为什么 HystrixCommand 对象只能使用一次。
猜你喜欢
  • 2018-09-16
  • 2016-11-26
  • 2015-04-13
  • 2018-07-15
  • 2011-08-29
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多