hystrix拒绝完全未来返回类型

polhcujo  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(414)

我正在努力纠正错误 @Hystrix 返回 CompltetableFuture<String> .

@HystrixCommand(fallbackMethod = "myMethodFallback")
public CompletableFuture<String> myMethod(){
  CompletableFuture<String> future = getFuture();
  return future;
}

public CompletableFuture<String> myMethodFallback(Throwable t){
  return CompletableFuture.completedFuture("");
}

但是,调用该方法时,会出现以下错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.netflix.hystrix.contrib.javanica.exception.FallbackDefinitionException: Incompatible return types. 
...
Hint: fallback cannot return Future if the fallback isn't command when the command is async.

我在某个地方读到,我可能会尝试更改fallbackmethod的返回类型,这样它就不会返回未来,而是返回泛型值。所以我试了这个:

public String myMethodFallback(Throwable t){
  return "";
}

出现了这个错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: com.netflix.hystrix.HystrixCommand$4 cannot be cast to java.util.concurrent.CompletableFuture

我到处玩,试着添加 @HystrixCommand 以及回退方法

@HystrixCommand
public CompletableFuture<String> myMethodFallback(Throwable t){
  return CompletableFuture.completedFuture("");
}

但有个错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: com.netflix.hystrix.contrib.javanica.utils.FutureDecorator cannot be cast to java.util.concurrent.CompletableFuture

有人对hystrix回退方法的限制有很好的了解吗?
我能在这里做些什么来让这一切顺利吗?或者只是不可能返回一个 Future 从hystrix方法?

sh7euo9m

sh7euo9m1#

下面是另一种使用springwebreactive和hystrixcommand的方法。

@Autowired
HystrixImpl hystrixImpl;

public Mono<String> getResponse() {

    return HystrixCommands.from(hystrixImpl.myMethod())
            .fallback(throwable -> {
                return hystrixImpl.myMethodFallback(throwable);
            })
            .commandName("MyCommand")
            .toFlux()
            .single();
}

hystriximpl.java文件

@Service 
public class HystrixImpl {
    public Mono<String> myMethod() {
        return Mono.just("From main method");
    }

    public Mono<String> myMethodFallback(Throwable t) {
        return Mono.just("From fallback method");
    }

}

我们只需要使用getresponse().block()来获取mono的字符串值。

相关问题