是否可以使java方法超时?

use*_*081 5 java

我需要执行ping Web服务来检查我是否已连接到端点,并且Web服务服务器一切正常。

这有点愚蠢,但我必须为此打电话给网络服务。问题是,当我调用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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Blo*_*je5 3

您可以使用Google Guava 库中的TimeLimiter之类的东西。这允许您将可调用对象包装在可以使用超时调用的操作中。如果可调用对象没有及时完成操作,它将抛出一个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
}
Run Code Online (Sandbox Code Playgroud)