有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hystrix拒绝完全未来返回类型

我正在尝试更正@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.

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

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
  1. 有人对Hystrix回退方法的限制有很好的了解吗
  2. 我能做些什么来让这一切顺利吗?或者是不可能从Hystrix方法返回Future

共 (1) 个答案

  1. # 1 楼答案

    下面是另一种使用Spring Web和HystrixCommand的方法

    @Autowired
    HystrixImpl hystrixImpl;
    
    public Mono<String> getResponse() {
    
        return HystrixCommands.from(hystrixImpl.myMethod())
                .fallback(throwable -> {
                    return hystrixImpl.myMethodFallback(throwable);
                })
                .commandName("MyCommand")
                .toFlux()
                .single();
    }
    

    希斯特里克西姆。爪哇

    @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的字符串值