我有一个库,为我们的客户提供了两种方法:同步和异步。他们可以根据自己的目的调用任何一种方法。
- executeSynchronous() - 等待直到获得结果,返回结果。
- executeAsynchronous() - 立即返回一个 Future 对象,如果需要,可以在完成其他事情后处理它。
他们将传递 DataKey 对象,其中包含用户 ID。我们将根据用户 ID 确定要调用哪台机器。因此,我们将使用 AsyncRestTemplate 进行 HTTP 调用,并根据是否成功将响应发送回给他们。
以下是我的接口:
public interface Client {
// for synchronous
public DataResponse executeSync(final DataKey key);
// for asynchronous
public Future<DataResponse> executeAsync(final DataKey key);
}
以下是我的实现:
public class DataClient implements IClient {
// does this have to be final?
private final AsyncRestTemplate restTemplate = new AsyncRestTemplate();
@Override
public DataResponse executeSync(final DataKey keys) {
Future<DataResponse> responseFuture = executeAsync(keys);
DataResponse response = null;
try {
response = responseFuture.get(keys.getTimeout(), TimeUnit.Milliseconds);
} catch (CancellationException e) {
// what to do here?
} catch (InterruptedException e) {
// is this right way to deal with InterruptedException?
throw new RuntimeException("Interrupted", e);
} catch (ExecutionException e) {
// what do you mean by ExecutionException? And how should we deal with this?
DataLogging.logErrors(e.getCause(), DataErrorEnum.ERROR_CLIENT, keys);
response = new DataResponse(null, DataErrorEnum.ERROR_CLIENT, DataStatusEnum.ERROR);
} catch (TimeoutException e) {
DataLogging.logErrors(e.getCause(), DataErrorEnum.TIMEOUT_ON_CLIENT, keys);
response = new DataResponse(null, DataErrorEnum.TIMEOUT_ON_CLIENT, DataStatusEnum.ERROR);
}
return response;
}
@Override
public Future<DataResponse> executeAsync(final DataKey keys) {
final SettableFuture<DataResponse> responseFuture = SettableFuture.create();
restTemplate.exchange(createURL(keys), HttpMethod.GET, keys.getEntity(), String.class).addCallback(
new ListenableFutureCallback<ResponseEntity<String>>() {
@Override
public void onSuccess(ResponseEntity<String> result) {
responseFuture.set(new DataResponse(result.getBody(), DataErrorEnum.OK,
DataStatusEnum.SUCCESS));
}
@Override
public void onFailure(Throwable ex) {
DataLogging.logErrors(ex, DataErrorEnum.ERROR_SERVER, keys);
responseFuture.set(new DataResponse(null, DataErrorEnum.ERROR_CLIENT,
DataStatusEnum.ERROR));
}
});
return responseFuture;
}
}
现在我的问题是:
- 在
executeSync
的catch块中如何正确处理异常?CancellationException和TimeoutException之间有什么区别?一般情况下我们应该如何处理ExecutionException
? - 我的DataKey在接口中必须是final的吗?如果我在executeAsync实现中删除final变量,则会出现编译错误,提示“无法引用在不同方法中定义的内部类中的非最终变量keys”。
- 这是在我的
executeAsync
方法中使用ListenableFutureCallback的正确方式吗?还是有更好的使用方法?