首页 > 解决方案 > 是否可以使 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;
        }
    }

标签: java

解决方案


您可以使用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
}

推荐阅读