高度な使用方法

このガイドでは、Java クライアント ライブラリの高度な側面をカスタマイズする方法について説明します。一般的なパターンは、これらの機能の多くが標準のコンビニエンス メソッドではなく、基盤となる Callable に依存していることです。呼び出し可能オブジェクトは、通常、ここに記載されていない RPC ごとの他の機能を探すのに適しています。

タイムアウト

Java ライブラリは、呼び出しごとにタイムアウトを設定するためのサーフェスを提供します。デフォルト値は、googleads_grpc_service_config.json の method_config/timeout 設定に基づいて設定されます。API 呼び出しの最大時間を短く制限する必要がある場合は、小さい値を設定します。

この機能を使用するには、Callable オブジェクトを直接呼び出します。たとえば、GoogleAdsService.searchStream() を呼び出すときに、次のようにタイムアウトを設定します。

try (GoogleAdsServiceClient googleAdsServiceClient =
    googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
  // Constructs the SearchGoogleAdsStreamRequest.
  SearchGoogleAdsStreamRequest request =
      SearchGoogleAdsStreamRequest.newBuilder()
          .setCustomerId(Long.toString(customerId))
          .setQuery("SELECT campaign.id, campaign.name FROM campaign")
          .build();

  // Executes the API call with a timeout of 5 minutes.
  ServerStream<SearchGoogleAdsStreamResponse> stream =
      googleAdsServiceClient
          .searchStreamCallable()
          .call(
              request,
              GrpcCallContext.createDefault()
                  .withTimeout(Duration.of(5, ChronoUnit.MINUTES)));
  for (SearchGoogleAdsStreamResponse response : stream) {
    // Processes the response rows.
  }
}

タイムアウトは 2 時間以上に設定できますが、API は実行時間が非常に長いリクエストをタイムアウトして DEADLINE_EXCEEDED エラーを返すことがあります。この問題が発生した場合は、通常、クエリを分割してチャンクを並行して実行するのが最善の方法です。これにより、長時間実行されるリクエストが失敗し、回復する唯一の方法が最初からリクエストを再度トリガーすることになる状況を回避できます。

再試行の設定

Java ライブラリには、呼び出しごとに再試行設定を構成するためのサーフェスも用意されています。この機能を使用するには、Callable オブジェクトを直接呼び出します。たとえば、GoogleAdsService.searchStream() を呼び出すときに、次のように再試行設定を構成します。

try (GoogleAdsServiceClient googleAdsServiceClient =
    googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
  SearchGoogleAdsStreamRequest request =
      SearchGoogleAdsStreamRequest.newBuilder()
          .setCustomerId(Long.toString(customerId))
          .setQuery("SELECT campaign.id, campaign.name FROM campaign")
          .build();

  // Creates a context object with the custom retry settings.
  GrpcCallContext context =
      GrpcCallContext.createDefault()
          .withRetrySettings(
              RetrySettings.newBuilder()
                  .setInitialRetryDelay(Duration.ofMillis(10L))
                  .setMaxRetryDelay(Duration.ofSeconds(10L))
                  .setRetryDelayMultiplier(1.4)
                  .setMaxAttempts(10)
                  .setLogicalTimeout(Duration.ofSeconds(30L))
                  .build());

  // Issues the streaming search request.
  ServerStream<SearchGoogleAdsStreamResponse> stream =
      googleAdsServiceClient.searchStreamCallable().call(request, context);
  for (SearchGoogleAdsStreamResponse response : stream) {
    // Processes the response rows.
  }
}

起動時間のパフォーマンスの最適化

GoogleAdsClient インスタンスが初めて作成されるときに、わずかな遅延が発生することがあります。これは、サービス(GoogleAdsClient.getLatestVersion())の Fluent インターフェースが、API サービス クラスを一度に読み込んで、サービス クライアントを構築するための便利なメカニズムを提供するためです。

初回リクエストのパフォーマンスがアプリケーションのクリティカル パスにある場合は、次の手順を行います。

  1. ユーザー リクエストを処理する前に、起動時に GoogleAdsClient を作成します。

  2. プロセスが最初に開始されたときに、Google Ads API にウォームアップ リクエストをいくつか送信します。次に例を示します。

    // Runs some warm-up requests.
    try (GoogleAdsServiceClient googleAdsServiceClient =
        googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
      // Runs 5 warm-up requests. In our profiling we see that 90% of
      // performance loss is only experienced on the first API call. After 3
      // subsequent calls we saw a negligible improvement in performance.
      for (int i = 0; i < 5; ++i) {
        // Warm-up queries are run with a nonexistent CID so the calls will
        // fail. If you have a CID that you know will be accessible with the
        // OAuth credentials provided you may want to provide that instead and
        // avoid the try-catch.
        try {
          googleAdsServiceClient.search("-1", "Warm-up query");
        } catch (ApiException ex) {
          // Do nothing, we're expecting this to fail.
        }
      }
    }
    

ウォームアップ リクエストは、プロセスごとに 1 回だけ実行する必要があります。以降のサービス クライアントの作成では、プリロードされたクラスが自動的に再利用されます。

サービス クライアントの再利用

GoogleAdsClient.getLatestVersion().createYYYServiceClient()(または getVersion25() などのバージョン固有のアクセサー)への呼び出しごとに新しい基盤となる接続と関連リソースが作成されるため、サービス クライアント インスタンスは可能な限り再利用する必要があります。

サービス クライアントが不要になったら、必ず閉じてください。これは、try-with-resources ブロックで行うか、サービス クライアントで close() を呼び出すことで行います。

クローズされたサービス クライアントを使用して API リクエストを送信しようとすると、サービス クライアント メソッドが java.util.concurrent.RejectedExecutionException をスローします。

JAR が 32 MB を超えると App Engine のデプロイが失敗する

App Engine では、アップロードするファイルごとに 32 MB の割り当てがあります。google-ads の JAR は、特にシェードまたはシャドー JAR のデプロイを使用する場合、これよりもかなり大きくなります。JAR を手動でデプロイすると、次のようなエラーが発生することがあります。

ERROR: (gcloud.app.deploy) Cannot upload file [<your-app>/WEB-INF/lib/google-ads-46.1.0.jar],
which has size [66095767] (greater than maximum allowed size of [33554432])

代わりに、App Engine の Gradle プラグインまたは Maven プラグインを使用してデプロイします。各プラグインには、各 JAR を 10 MB のチャンクに分割してアップロードする enableJarSplitting オプションが用意されています。

シャドウの依存関係

プロジェクトにライブラリの依存関係と競合する依存関係がある場合は、次のいずれかのコマンドを使用してプロジェクトの依存関係の階層を調べ、必要に応じてプロジェクトの依存関係を変更します(または、部品構成表を使用します)。

Maven

mvn dependency:tree

Gradle

./gradlew dependencies

依存関係の競合を解決できない場合は、ライブラリの shaded バージョンに依存できます。

Maven

<dependency>
  <groupId>com.google.api-ads</groupId>
  <artifactId>google-ads-shadowjar</artifactId>
  <version>46.1.0</version>
</dependency>

Gradle

implementation 'com.google.api-ads:google-ads-shadowjar:46.1.0'