【问题标题】:Hystrix refuses Completable Future return TypeHystrix 拒绝 Completable Future 返回类型
【发布时间】:2021-03-02 07:52:34
【问题描述】:

我正在尝试纠正返回 CompltetableFuture<String>@Hystrix 方法。

@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
  1. 是否有人对 Hystrix 后备方法的限制有很好的资源?
  2. 我可以在这里做些什么来完成这项工作吗?还是不能从 Hystrix 方法返回 Future

【问题讨论】:

  • 这些是一些有趣的无用错误消息。

标签: java completable-future hystrix


【解决方案1】:

这是使用带有 HystrixCommand 的 Spring Web 反应式的替代方法。

@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 的 String 值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2019-07-08
    相关资源
    最近更新 更多