進階用法

本指南說明如何自訂 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()) 會一次載入 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.
        }
      }
    }
    

每個程序只需執行一次暖機要求。後續建立的每個服務用戶端都會自動重複使用預先載入的類別。

重複使用服務用戶端

在實務上,您應重複使用服務用戶端例項,因為每次呼叫 GoogleAdsClient.getLatestVersion().createYYYServiceClient() (或 getVersion26() 等特定版本的存取子) 時,都會建立新的基礎連線和相關聯的資源。

請務必在不再需要服務用戶端時將其關閉。您可以在 try-with-resources 區塊中執行這項操作,也可以呼叫服務用戶端上的 close()。

如果您嘗試使用已關閉的服務用戶端提出 API 要求,服務用戶端方法會擲回 java.util.concurrent.RejectedExecutionException。

如果 JAR 大於 32 MB,App Engine 就無法部署

App Engine 對每個上傳檔案的配額為 32 MB。google-ads 的 JAR 遠大於此,尤其是在使用 shade 或 shadow JAR 部署時。如果手動部署 JAR,可能會收到以下錯誤訊息:

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

請改用 App Engine Gradle 外掛程式或 Maven 外掛程式進行部署。每個外掛程式都提供 enableJarSplitting 選項,可將每個 JAR 分割成 10 MB 的區塊,並改為上傳這些區塊。

影子依附元件

如果專案的依附元件與程式庫的依附元件衝突,請使用下列其中一個指令檢查專案的依附元件階層,然後視需要修改專案的依附元件 (或使用物料清單):

Maven

mvn dependency:tree

Gradle

./gradlew dependencies

如果無法解決依附元件衝突,可以改為依附遮蔽版本的程式庫:

Maven

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

Gradle

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