首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将Spring-REST中的@异步方法转换为带有异步回退的异步@HystrixCommand方法

将Spring-REST中的@异步方法转换为带有异步回退的异步@HystrixCommand方法
EN

Stack Overflow用户
提问于 2018-01-08 15:04:34
回答 1查看 863关注 0票数 0

在我的@Service类中,我有一个被标记为@异步的方法。这将返回一个未来类型。

这个方法基本上是一个客户端,它在另一个URL中调用一个服务(此处标记为URL)。

代码语言:javascript
复制
@Async
public Future<Object> performOperation(String requestString) throws InterruptedException {
Client client = null;
WebResource webResource = null;
ClientResponse response = null;
String results = null;

try {
client=Client.create();
webResource = client.resource(URL);
client.setConnectTimeout(10000);
client.setReadTimeout(10000);
response = webResource.type("application/xml").post(ClientResponse.class,requestString);
if(response.getStatus()!=200) {
   webResource=null;
   logger.error("request failed with HTTP Status: " + response.getStatus());
   throw new RuntimeException("request failed with HTTP Status: " + response.getStatus());
  }
results=response.getEntity(String.class);
 } finally {
    client.destroy();
    webResource=null;
    }
   return new AsyncResult<>(results);
}

我希望以以下格式将此@异步方法转换为异步@HystrixCommand方法:

代码语言:javascript
复制
@HystrixCommand
    public Future<Object> performOperation(String requestString) throws InterruptedException {
        return new AsyncResult<Object>() {

            @Override
            public Product invoke() {
                ...
                return results;
            }
        };
    }

但是,当我这样做时,它会在我的代码中抛出以下错误:

对于return new AsyncResult<Object>() {...}这一行,它说

构造器AsyncResult()未定义。

当我要求Eclipse修复错误时,它将requestString对象添加到构造函数参数(即AsyncResult<Object>(requestString) )中

此外,它还要求我从@Override方法中删除该invoke()

它说

类型为new AsyncResult(){}的方法调用()必须重写或实现超类型方法。

但是,当要求eclipse为我修复错误时,它会删除@Override

我的问题是如何将@异步方法变成异步@HystrixCommand方法,而不存在任何这些问题?

我还想为这个方法实现一个异步回退,如果响应状态代码不是200,它会向用户显示一条默认消息。

我该怎么做呢?

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2018-01-08 15:20:02

从这条信息

还要求我从invoke()方法中删除@重写。

而不是com.netflix.hystrix.contrib.javanica.command.AsyncResult

更改类型应该可以解决问题。

您可以提供一个类似于在同步方法情况下如何执行的回退。

代码语言:javascript
复制
@HystrixCommand(fallbackMethod="myFallbackMethod")
    public Future<Object> performOperation(String requestString) throws InterruptedException {
        return new AsyncResult<Object>() {

            @Override
            public Product invoke() {
                ...
                return results;
            }
        };
    }

 public Future<Object> myFallbackMethod(String requestString) {
      return new AsyncResult<Object>() {

            @Override
            public Product invoke() {
               ....... // return some predefined results;
            }

   }

还有一件事。而不是宣布为精灵Object。将其指定为像Product这样的任何具体类型

代码语言:javascript
复制
public Future<Product> performOperation(String requestString) throws InterruptedException {
   .....


 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48152910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档