דחיסת הודעות

אם אתם משתמשים ב-Pub/Sub כדי לפרסם הודעות שמצטברות לכמות גדולה של נתונים, אתם יכולים להשתמש ב-gRPC כדי לדחוס את הנתונים ולחסוך בעלויות הרשת לפני שלקוח המפרסם שולח את בקשת הפרסום. הדחיסה ב-Pub/Sub עבור gRPC מתבצעת באמצעות האלגוריתם Gzip.

במסמך הזה מוסבר איך לדחוס הודעות שמתפרסמות בנושא.

מידע על דחיסת הודעות

יחס הדחיסה של התכונה לדחיסה בצד הלקוח ב-gRPC שונה עבור לקוחות שונים של בעלי תוכן דיגיטלי, ותלוי בגורמים הבאים:

  • כמות הנתונים. יחס הדחיסה משתפר כשהגודל של מטען הייעודי (payload) גדל מכמה מאות בייטים לכמה קילובייטים של נתונים. הגדרות האצווה של בקשת פרסום קובעות את כמות הנתונים שנכללת בכל בקשת פרסום. כדי לקבל את התוצאות הטובות ביותר, מומלץ להפעיל את הגדרות האצווה בשילוב עם דחיסת gRPC.

  • סוג הנתונים נתונים מבוססי-טקסט כמו JSON או XML ניתנים לדחיסה יותר בקלות בהשוואה לנתונים בינאריים כמו תמונות.

אם חשבון הלקוח של בעל התוכן הדיגיטלי נמצא ב- Google Cloud, אפשר להשתמש במדד Sent bytes (instance/network/sent_bytes_count) כדי למדוד את קצב העברת הנתונים של התוכן הדיגיטלי בבייטים. אם לקוח בעל אתר חדשות נמצא באפליקציה אחרת, צריך להשתמש בכלים ספציפיים ללקוח כדי לבצע את המדידה.

דוגמת הקוד בקטע הזה מציגה קטע קוד לדוגמה של ספריית לקוח ב-Java, שכולל גם דחיסה של gRPC.

לפני שמתחילים

לפני שמגדירים את תהליך העבודה של הפרסום, צריך לוודא שביצעתם את המשימות הבאות:

התפקידים הנדרשים

כדי לקבל את ההרשאות שנדרשות לדחיסת הודעות, צריך לבקש מהאדמין להקצות לכם ב-IAM את התפקיד פרסום הודעות ב-Pub/Sub (roles/pubsub.publisher) בנושא. כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

כדי ליצור או לעדכן נושאים ומינויים, צריך הרשאות נוספות.

דחיסת הודעה

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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של 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);
      }
    }
  }
}

המאמרים הבאים

כדי ללמוד איך מגדירים אפשרויות פרסום מתקדמות, אפשר לעיין במאמרים הבאים: