长时间运行的操作 (LRO)

对该 API 的多次调用会返回长时间运行的操作。这些代码可跟踪 也就是在较长时间内执行的作业, 但并不希望阻止 RPC。

OperationFuture 类

与 LRO 交互的最明显方法是 OperationFuture 类。如果您使用此方法,请确保服务客户端不会被销毁。

不推荐:

private void doSomething() {
  OperationFuture<Empty, Empty> future = startLongRunningOperation(jobName);
  future.get();
}

private OperationFuture<Empty, Empty> startLongRunningOperation(String jobToStart)
    throws UnsupportedEncodingException {
  try (OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
      googleAdsClient.getLatestVersion().createOfflineUserDataJobServiceClient()) {
    // Issues an asynchronous request to run the offline user data job for executing
    // all added operations.
    return offlineUserDataJobServiceClient.runOfflineUserDataJobAsync(jobToStart);
  }
}

推荐:

private void doSomethingElse() {
  try (OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
      googleAdsClient.getLatestVersion().createOfflineUserDataJobServiceClient()) {
    OperationFuture<Empty, Empty> future = startLongRunningOperation(offlineUserDataJobServiceClient, jobName);
    future.get();
  }
}

private OperationFuture<Empty, Empty> startLongRunningOperation(String jobToStart)
    throws UnsupportedEncodingException {
    offlineUserDataJobServiceClient.runOfflineUserDataJobAsync(jobToStart);
}

请注意,OperationFuture 类仅在 OfflineUserDataJobServiceClient在范围内。