java - 如何在 JAVA 中设置 Web 服务调用超时?
问题描述
您好,我必须更新我公司的应用程序,所以我必须在调用客户端的 Web 服务时添加超时(我只是关于 Spring 框架的提示)。我怎样才能做到这一点 ?
我有一个可以调用某个客户端的 Web 服务的应用程序,我必须在应用程序选择它必须调用的 Web 服务时添加一个超时。
我研究了 Spring 注解,以及其他关于 JAVA 超时的事情。大多数解决方案是直接在 SOAP/REST 调用上设置超时,但我没有成功使用这些解决方案。此外,我必须在代码中将超时设置得更高/更早。而且,所有客户端的 Web 服务都有不同的调用方式(身份验证与否,令牌 ID ...)。
这是选择调用哪个客户端的 Web 服务并调用方法“findSubscriber”来调用将使用我们的技术块调用 Web 服务的客户端实现的代码提示。订阅者是需要某些东西的人。一个客户有很多订阅者。我们为很多客户工作。
...
@Override
public ResearchReturn findSubscribers(ResearcheElements researcheElements) throws SubscriberException {
ResearchReturn rReturn = null;
try {
String countryCode = researcheElements.getCountryCode();
String clientCode = researcheElements.getClientCode();
// [Some tests and things...]
// We get the way of the client's Implementation depending the countryCode and clientCode
findSubscribersService service = (findSubscribersService) getService().getRoute(countryCode, clientCode, "findSubscribersService");
do {
// Call of the client's Implementation depending of the way that is in "service"
rReturn = service.findSubscribers(researcheElements);
List<Subscribers> subs = subsFilter(researcheElements.getResearchCriteria(), rReturn.getSubscribers());
[...]
} while ([...]);
[...]
} catch (NonDispoException nde) {
[...]
} catch (SubscriberException e) {
[...]
} catch (Exception e) {
[...]
}
return rReturn;
}
...
所以我希望调用一个网络服务,如果服务在 10 秒后没有响应,我会尝试在我们的数据库中找到订阅者。但实际上我调用了一个客户端 Web 服务,如果它没有响应,我会发送一条错误消息。我想我必须对对象“rReturn”进行超时。(对不起,我的英语不好)。
谢谢你的帮助。
编辑:我得到了一个新提示,我可能可以在 Spring 设置中设置超时。
编辑:我使用FutureTask
package com.sdzee.beans;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> timeoutTask = null;
try {
timeoutTask = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
return "Ready!";
}
});
System.out.println("Started..");
new Thread(timeoutTask).start();
// Here we call the method call()
System.out.println(timeoutTask.get(3L, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (TimeoutException e) {
// Terminate the thread
timeoutTask.cancel(true);
System.out.println("Timeout!");
}
}
}
结果 :
开始..超时!
解决方案
推荐阅读
- python - 如何绘制多元线性回归的输出?
- git - Git忽略目录中的所有内容,但一种文件类型
- r - 如何找到两个单词模式只知道r中的第一个
- excel - 根据最新日期删除重复行
- python - 除以零时获得无穷大
- java - 用 Java 开发一个可重用的模板项目
- javascript - 当转换为 json2csv 时,所有标题和数据都来自相同的列。我们如何分离这些列?
- angular - 通过订阅主题()更新值后如何以角度重新渲染组件
- pentaho - 为什么 Kitchen 无法识别我的存储库?
- google-app-engine - 尝试将值附加到 wtforms 验证器时,为什么我在谷歌应用程序引擎上遇到烧瓶超时异常?