고급 사용법

이 가이드에서는 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() (또는 getVersion25()와 같은 버전별 접근자)에 대한 각 호출은 새로운 기본 연결과 연결된 리소스를 생성하므로 가능한 경우 서비스 클라이언트 인스턴스를 재사용해야 합니다.

더 이상 필요하지 않은 경우 서비스 클라이언트를 닫아야 합니다. try-with-resources 블록에서 또는 서비스 클라이언트에서 close()를 호출하여 이를 실행할 수 있습니다.

종료된 서비스 클라이언트를 사용하여 API 요청을 시도하면 서비스 클라이언트 메서드가 java.util.concurrent.RejectedExecutionException를 발생시킵니다.

JAR이 32MB를 초과하면 App Engine 배포가 실패함

App Engine에는 업로드된 파일당 32MB의 할당량이 있습니다. google-ads의 JAR는 특히 셰이드 또는 섀도우 JAR 배포를 사용하는 경우 이보다 훨씬 큽니다. JAR를 수동으로 배포하면 다음과 같은 오류가 발생할 수 있습니다.

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

대신 App Engine Gradle 플러그인 또는 Maven 플러그인을 사용하여 배포하세요. 각 플러그인은 각 JAR를 10MB 청크로 분할하고 이를 대신 업로드하는 enableJarSplitting 옵션을 제공합니다.

섀도우 종속 항목

프로젝트에 라이브러리의 종속 항목과 충돌하는 종속 항목이 있는 경우 다음 명령 중 하나를 사용하여 프로젝트의 종속 항목 계층 구조를 검사한 다음 필요에 따라 프로젝트의 종속 항목을 수정합니다 (또는 BOM 사용).

Maven

mvn dependency:tree

Gradle

./gradlew dependencies

종속 항목 충돌을 해결할 수 없는 경우 라이브러리의 shaded 버전을 대신 사용할 수 있습니다.

Maven

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

Gradle

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