java - 是否可以使 java 方法超时?
问题描述
我需要执行一个 ping webservice 来检查我是否连接到端点并且 webservice 服务器一切正常。
这有点愚蠢,但我必须为此调用网络服务。问题是,当我调用stub.ping(request)
并且我没有连接时,它会一直尝试执行此代码一分钟......然后返回false。
如果无法 ping,有什么方法可以在 1 秒后超时?
public boolean ping() {
try {
PingServiceStub stub = new PingServiceStub(soapGWEndpoint);
ReqPing request = new ReqPing();
UserInfo userInfo = new UserInfo();
userInfo.setName(soapGWUser);
userInfo.setPassword(soapGWPassword);
ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.setConfigurationName(soapGWAppName);
stub.ping(request);
return true;
} catch (RemoteException | PingFault e) {
return false;
}
}
解决方案
您可以使用Google Guava 库中的TimeLimiter之类的东西。这允许您将可调用对象包装在可以使用 Timeout 调用的操作中。如果 callable 没有及时完成操作,它会抛出一个TimeoutException
你可以捕获的,一秒后返回 false。
举个例子:
TimeLimiter timeLimiter = new SimpleTimeLimiter();
try {
String result = timeLimiter.callWithTimeout(
() -> callToPing(), 1, TimeUnit.SECONDS);
return true // Or something based on result
} catch (TimeoutException e) {
return false
}
推荐阅读
- css - 向 shadowDOM 中动态创建的样式表添加规则
- logstash - Cloudfront 登录 Prometheus
- c# - (a,b) = (1,2) 是什么意思?
- python - 在 Python 中循环正则表达式,直到输入正确
- javascript - 限制js文件内容的范围
- javascript - 在 React 应用程序中更新动态呈现的元素的问题
- python - 在通过 Python 使用 Root 中创建带有分支的 TTree
- rest - 如何使用支持 Rest 和 GraphQL 的 light-4j 构建应用程序
- amazon-cloudfront - 缓存与无缓存是否会影响 CloudFront 定价?
- typescript - TypeScript:让库的用户定义类型