在我的@Service类中,我有一个被标记为@异步的方法。这将返回一个未来类型。
这个方法基本上是一个客户端,它在另一个URL中调用一个服务(此处标记为URL)。
@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方法:
@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,它会向用户显示一条默认消息。
我该怎么做呢?
谢谢。
发布于 2018-01-08 15:20:02
从这条信息
还要求我从invoke()方法中删除@重写。
而不是com.netflix.hystrix.contrib.javanica.command.AsyncResult。
更改类型应该可以解决问题。
您可以提供一个类似于在同步方法情况下如何执行的回退。
@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这样的任何具体类型
public Future<Product> performOperation(String requestString) throws InterruptedException {
.....
}https://stackoverflow.com/questions/48152910
复制相似问题