Hystrix 拒绝 Completable Future 返回类型

Posted

技术标签:

【中文标题】Hystrix 拒绝 Completable Future 返回类型【英文标题】:Hystrix refuses Completable Future return Type 【发布时间】: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
    是否有人对 Hystrix 后备方法的限制有很好的资源? 我可以在这里做些什么来完成这项工作吗?还是不能从 Hystrix 方法返回 Future

【问题讨论】:

这些是一些有趣的无用错误消息。 【参考方案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 值。

【讨论】:

以上是关于Hystrix 拒绝 Completable Future 返回类型的主要内容,如果未能解决你的问题,请参考以下文章

Feign - Hystrix - feign.RetryableException:连接被拒绝:没有更多信息执行 GET

如何在 RxJava2 中链接两个 Completable

Hystrix线程池配置

RxSwift: 链 Completable 到 Observable

RXJAVA-Completable

RXJAVA-Completable