메시지 압축

Pub/Sub을 사용하여 데이터를 대량으로 게시하는 경우 게시자 클라이언트에서 게시 요청을 보내기 전에 gRPC를 사용하여 데이터를 압축하면 네트워킹 비용이 절약됩니다. gRPC용 Pub/Sub 압축은 Gzip 알고리즘을 사용합니다.

이 문서에서는 주제에 게시된 메시지를 압축하는 방법을 설명합니다.

메시지 압축 정보

gRPC 클라이언트 측 압축 기능을 사용하는 압축 비율은 게시자 클라이언트마다 다르며 다음 요소에 따라 달라집니다.

  • 데이터 양. 페이로드 크기가 수백 바이트 데이터에서 수 킬로바이트 데이터로 증가하면 압축 비율이 향상됩니다. 게시 요청의 일괄 설정은 각 게시 요청에 포함되는 데이터 양을 결정합니다. 최상의 결과를 얻으려면 gRPC 압축과 함께 일괄 설정을 사용 설정하는 것이 좋습니다.

  • 데이터 유형. JSON 또는 XML과 같은 텍스트 기반 데이터는 이미지와 같은 바이너리 데이터보다 더 압축할 수 있습니다.

Google Cloud에 게시자 클라이언트가 있으면 전송된 바이트(instance/network/sent_bytes_count) 측정항목을 사용하여 게시 처리량(바이트 단위)을 측정할 수 있습니다. 게시자 클라이언트가 다른 애플리케이션에 있는 경우 측정하려면 클라이언트별 도구를 사용해야 합니다.

이 섹션의 코드 샘플에서는 gRPC 압축도 포함된 샘플 Java 클라이언트 라이브러리 코드 스니펫을 보여줍니다.

시작하기 전에

게시 워크플로를 구성하기 전에 다음 작업이 완료되어야 합니다.

필요한 역할

메시지 압축에 필요한 권한을 얻으려면 관리자에게 문의해서 주제에 대해 Pub/Sub 게시자(roles/pubsub.publisher) IAM 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 액세스 관리를 참조하세요.

커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

주제 및 구독을 만들거나 업데이트하려면 추가 권한이 필요합니다.

메시지 압축

C++

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 C++ 설정 안내를 따르세요. 자세한 내용은 Pub/Sub C++ API 참고 문서를 확인하세요.

namespace g = ::google::cloud;
namespace pubsub = ::google::cloud::pubsub;
[](std::string project_id, std::string topic_id) {
  auto topic = pubsub::Topic(std::move(project_id), std::move(topic_id));
  auto publisher = pubsub::Publisher(pubsub::MakePublisherConnection(
      std::move(topic),
      g::Options{}
          // Compress any batch of messages over 10 bytes. By default, no
          // messages are compressed, set this to 0 to compress all batches,
          // regardless of their size.
          .set<pubsub::CompressionThresholdOption>(10)
          // Compress using the GZIP algorithm. By default, the library uses
          // GRPC_COMPRESS_DEFLATE.
          .set<pubsub::CompressionAlgorithmOption>(GRPC_COMPRESS_GZIP)));
  auto message_id = publisher.Publish(
      pubsub::MessageBuilder{}.SetData("Hello World!").Build());
  auto done = message_id.then([](g::future<g::StatusOr<std::string>> f) {
    auto id = f.get();
    if (!id) throw std::move(id).status();
    std::cout << "Hello World! published with id=" << *id << "\n";
  });
  // Block until the message is published
  done.get();
}

Java

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 자바 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Java API 참고 문서를 참조하세요.

import com.google.api.core.ApiFuture;
import com.google.cloud.pubsub.v1.Publisher;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class PublishWithGrpcCompressionExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    // Choose an existing topic.
    String topicId = "your-topic-id";

    publishWithGrpcCompressionExample(projectId, topicId);
  }

  public static void publishWithGrpcCompressionExample(String projectId, String topicId)
      throws IOException, ExecutionException, InterruptedException {
    TopicName topicName = TopicName.of(projectId, topicId);

    // Create a publisher and set enable compression to true.
    Publisher publisher = null;
    try {
      // Enable compression and configure the compression threshold to 10 bytes (default to 240 B).
      // Publish requests of sizes > 10 B (excluding the request headers) will get compressed.
      // The number of messages in a publish request is determined by publisher batch settings.
      // Batching is turned off by default, i.e. each publish request contains only one message.
      publisher =
          Publisher.newBuilder(topicName)
              .setEnableCompression(true)
              .setCompressionBytesThreshold(10L)
              .build();

      byte[] bytes = new byte[1024];
      ByteString data = ByteString.copyFrom(bytes);
      PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();

      // Once published, returns a server-assigned message id (unique within the topic).
      // You can look up the actual size of the outbound data using the Java Logging API.
      // Configure logging properties as shown in
      // https://github.com/googleapis/java-pubsub/tree/main/samples/snippets/src/main/resources/logging.properties
      // and look for "OUTBOUND DATA" with "length=" in the output log.
      ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
      String messageId = messageIdFuture.get();
      System.out.println("Published a compressed message of message ID: " + messageId);
    } finally {
      if (publisher != null) {
        // When finished with the publisher, shutdown to free up resources.
        publisher.shutdown();
        publisher.awaitTermination(1, TimeUnit.MINUTES);
      }
    }
  }
}

다음 단계

고급 게시 옵션을 구성하는 방법은 다음을 참조하세요.