Pengiriman tepat satu kali

Halaman ini menjelaskan cara menerima dan mengonfirmasi pesan menggunakan fitur tepat satu kali Pub/Sub, yang memungkinkan Anda melacak dan mencegah pemrosesan pesan duplikat. Jika fitur ini diaktifkan, Pub/Sub akan memberikan semantik berikut:

  • Subscriber dapat menentukan apakah konfirmasi pesan berhasil.

  • Tidak ada pengiriman ulang yang terjadi setelah pesan berhasil dikonfirmasi.

  • Tidak ada pengiriman ulang yang terjadi saat pesan belum selesai diproses. Pesan dianggap belum selesai hingga batas waktu konfirmasi berakhir atau pesan dikonfirmasi.

  • Jika ada beberapa pengiriman yang valid, karena masa berlaku batas waktu konfirmasi habis atau konfirmasi negatif yang dimulai klien, hanya ID konfirmasi terbaru yang dapat digunakan untuk mengonfirmasi pesan. Setiap permintaan dengan ID konfirmasi sebelumnya akan gagal.

Dengan mengaktifkan pengiriman tepat satu kali, pelanggan dapat memastikan pesan diproses satu kali dengan mengikuti panduan berikut:

  • Konfirmasi pesan dalam batas waktu konfirmasi.

  • Menyimpan informasi tentang progres pemrosesan pesan hingga pesan berhasil dikonfirmasi.

  • Gunakan informasi tentang progres pemrosesan pesan untuk mencegah pekerjaan duplikat saat konfirmasi gagal.

Hanya jenis langganan pull yang mendukung pengiriman tepat satu kali, termasuk pelanggan yang menggunakan StreamingPull API. Langganan push dan ekspor tidak mendukung pengiriman tepat satu kali.

Pub/Sub mendukung pengiriman tepat satu kali, dalam region cloud, berdasarkan ID pesan unik yang ditentukan Pub/Sub.

Pengiriman ulang versus duplikat

Penting untuk memahami perbedaan antara pengiriman ulang yang diharapkan dan yang tidak diharapkan.

  • Pengiriman ulang dapat terjadi karena konfirmasi negatif yang dimulai klien atas pesan atau saat klien tidak memperpanjang batas waktu konfirmasi pesan sebelum batas waktu konfirmasi berakhir. Pengiriman ulang dianggap valid dan sistem berfungsi sebagaimana mestinya.

    Untuk memecahkan masalah pengiriman ulang, lihat Menangani duplikat.

  • Duplikat adalah saat pesan dikirim ulang setelah konfirmasi berhasil atau sebelum batas waktu konfirmasi berakhir.

  • Pesan yang dikirim ulang mempertahankan ID pesan yang sama di antara upaya pengiriman ulang.

Langganan yang mengaktifkan pengiriman tepat satu kali tidak akan menerima pengiriman duplikat.

Dukungan pengiriman tepat satu kali di library klien

  • Library klien yang didukung memiliki antarmuka untuk konfirmasi dengan respons (contoh: Go). Anda dapat menggunakan antarmuka ini untuk memeriksa apakah permintaan konfirmasi berhasil. Jika permintaan konfirmasi berhasil, klien dijamin tidak akan menerima pengiriman ulang. Jika permintaan konfirmasi gagal, klien dapat mengharapkan pengiriman ulang.

  • Klien juga dapat menggunakan library klien yang didukung tanpa antarmuka konfirmasi. Namun, dalam kasus seperti ini, kegagalan konfirmasi dapat menyebabkan pengiriman ulang pesan secara otomatis.

  • Library klien yang didukung memiliki antarmuka untuk menetapkan waktu perpanjangan sewa minimum (contoh: Go). Anda harus menetapkan nilai untuk perpanjangan sewa minimum ke angka yang tinggi untuk menghindari masa berlaku konfirmasi terkait jaringan. Nilai maksimum ditetapkan pada 600 detik.

  • Jika Anda menggunakan library klien Java dan menginisialisasi pelanggan dengan Saluran gRPC kustom menggunakan metode setChannelProvider(), sebaiknya tetapkan juga maxInboundMetadataSize ke setidaknya 1 MB saat membangun TransportChannelProvider. Untuk konfigurasi ini, Anda dapat menggunakan metode InstantiatingGrpcChannelProvider.Builder.setMaxInboundMetadataSize() atau ManagedChannelBuilder.maxInboundMetadataSize().

Nilai default dan rentang untuk variabel yang terkait dengan pengiriman tepat satu kali dan nama variabel mungkin berbeda di berbagai library klien. Misalnya, di library klien Java, variabel berikut mengontrol pengiriman tepat satu kali.

Variabel Deskripsi Nilai
setEnableExactlyOnceDelivery Mengaktifkan atau menonaktifkan pengiriman tepat satu kali. true atau false Default=false
minDurationPerAckExtension Waktu minimum dalam detik yang digunakan untuk memperpanjang batas waktu konfirmasi perubahan. Rentang=0 hingga 600 Default=tidak ada
maxDurationPerAckExtension Waktu maksimum dalam detik yang akan digunakan untuk memperpanjang batas waktu pengubahan konfirmasi. Rentang=0 hingga 600 Default=tidak ada

Dalam kasus pengiriman tepat satu kali, permintaan modifyAckDeadline atau acknowledgment ke Pub/Sub akan gagal jika ID konfirmasi sudah tidak berlaku. Dalam kasus seperti ini, layanan menganggap ID konfirmasi yang sudah tidak berlaku sebagai tidak valid, karena pengiriman yang lebih baru mungkin sudah dalam proses. Hal ini sesuai dengan desain untuk pengiriman tepat satu kali. Kemudian, Anda akan melihat permintaan acknowledgment dan ModifyAckDeadline menampilkan respons INVALID_ARGUMENT. Jika pengiriman tepat satu kali dinonaktifkan, permintaan ini akan menampilkan OK jika ID konfirmasi sudah tidak berlaku.

Untuk memastikan bahwa permintaan acknowledgment dan ModifyAckDeadline memiliki ID konfirmasi yang valid, pertimbangkan untuk menetapkan nilai minDurationPerAckExtension ke angka yang tinggi.

Pertimbangan regional

Jaminan pengiriman tepat satu kali hanya berlaku jika pelanggan terhubung ke layanan di region yang sama. Jika aplikasi pelanggan Anda tersebar di beberapa region, hal ini dapat menyebabkan pengiriman pesan duplikat, meskipun pengiriman tepat satu kali diaktifkan. Penayang dapat mengirim pesan ke region mana pun dan jaminan tepat satu kali masih dipertahankan.

Saat Anda menjalankan aplikasi dalam Google Cloud, secara default aplikasi tersebut akan terhubung ke endpoint Pub/Sub di region yang sama. Oleh karena itu, menjalankan aplikasi Anda di satu region dalam Google Cloud umumnya memastikan Anda berinteraksi dengan satu region.

Saat menjalankan aplikasi pelanggan di luar Google Cloud atau di beberapa region, Anda dapat menjamin bahwa Anda terhubung ke satu region dengan menggunakan endpoint lokasi saat mengonfigurasi klien Pub/Sub. Semua endpoint lokasi untuk Pub/Sub mengarah ke satu region. Untuk mempelajari endpoint lokasi lebih lanjut, lihat endpoint Pub/Sub. Untuk mengetahui daftar semua endpoint lokasi untuk Pub/Sub, lihat Daftar endpoint lokasi.

Membuat langganan dengan pengiriman tepat satu kali

Anda dapat membuat langganan dengan pengiriman tepat satu kali menggunakan konsol Google Cloud , Google Cloud CLI, library klien, atau Pub/Sub API.

Konsol

Untuk membuat langganan pull dengan pengiriman tepat satu kali, ikuti langkah-langkah berikut:

  1. Di konsol Google Cloud , buka halaman Subscriptions.

    Buka Langganan

  2. Klik Create subscription.

  3. Masukkan ID Langganan.

  4. Pilih atau buat topik dari menu drop-down.

    Langganan menerima pesan dari topik.

  5. Di bagian Exactly once delivery, pilih Enable exactly once delivery.

  6. Klik Create.

gcloud

Untuk membuat langganan pull dengan pengiriman tepat satu kali, gunakan perintah gcloud pubsub subscriptions create dengan flag --enable-exactly-once-delivery:

gcloud pubsub subscriptions create SUBSCRIPTION_ID \
  --topic=TOPIC_ID \
  --enable-exactly-once-delivery

Ganti kode berikut:

  • SUBSCRIPTION_ID: ID langganan yang akan dibuat
  • TOPIC_ID: ID topik yang akan dilampirkan ke langganan

REST

Untuk membuat langganan dengan pengiriman tepat satu kali, gunakan metode projects.subscriptions.create.

PUT https://pubsub.googleapis.com/v1/projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID
Authorization: Bearer $(gcloud auth print-access-token)

Ganti kode berikut:

  • PROJECT_ID: project ID untuk project tempat langganan akan dibuat
  • SUBSCRIPTION_ID: ID langganan yang akan dibuat

Untuk membuat langganan pull dengan pengiriman tepat satu kali, tentukan hal ini dalam isi permintaan:

{
  "topic": "projects/PROJECT_ID/topics/TOPIC_ID",
  "enableExactlyOnceDelivery": true,
}

Ganti kode berikut:

  • PROJECT_ID: project ID untuk project dengan topik
  • TOPIC_ID: ID topik yang akan dilampirkan ke langganan

C++

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C++ di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C++ Pub/Sub.

namespace pubsub = ::google::cloud::pubsub;
namespace pubsub_admin = ::google::cloud::pubsub_admin;
[](pubsub_admin::SubscriptionAdminClient client,
   std::string const& project_id, std::string const& topic_id,
   std::string const& subscription_id) {
  google::pubsub::v1::Subscription request;
  request.set_name(
      pubsub::Subscription(project_id, subscription_id).FullName());
  request.set_topic(pubsub::Topic(project_id, topic_id).FullName());
  request.set_enable_exactly_once_delivery(true);
  auto sub = client.CreateSubscription(request);
  if (sub.status().code() == google::cloud::StatusCode::kAlreadyExists) {
    std::cout << "The subscription already exists\n";
    return;
  }
  if (!sub) throw std::move(sub).status();

  std::cout << "The subscription was successfully created: "
            << sub->DebugString() << "\n";
}

C#

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C# di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C# Pub/Sub.


using Google.Cloud.PubSub.V1;
using Grpc.Core;

public class CreateSubscriptionWithExactlyOnceDeliverySample
{
    public Subscription CreateSubscriptionWithExactlyOnceDelivery(string projectId, string topicId, string subscriptionId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        var subscriptionRequest = new Subscription
        {
            SubscriptionName = subscriptionName,
            TopicAsTopicName = topicName,
            EnableExactlyOnceDelivery = true
        };

        Subscription subscription = null;

        try
        {
            subscription = subscriber.CreateSubscription(subscriptionRequest);
        }
        catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)
        {
            // Already exists.  That's fine.
        }
        return subscription;
    }
}

Go

Contoh berikut menggunakan versi utama library klien Pub/Sub Go (v2). Jika Anda masih menggunakan library v1, lihat panduan migrasi ke v2. Untuk melihat daftar contoh kode v1, lihat contoh kode yang tidak digunakan lagi.

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Pub/Sub.

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub/v2"
	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
)

func createSubscriptionWithExactlyOnceDelivery(w io.Writer, projectID, topic, subscription string) error {
	// projectID := "my-project-id"
	// topic := "projects/my-project-id/topics/my-topic"
	// subscription := "projects/my-project/subscriptions/my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	pbSub := &pubsubpb.Subscription{
		Name:                      subscription,
		Topic:                     topic,
		EnableExactlyOnceDelivery: true,
	}
	sub, err := client.SubscriptionAdminClient.CreateSubscription(ctx, pbSub)
	if err != nil {
		return fmt.Errorf("failed to create exactly once sub: %w", err)
	}
	fmt.Fprintf(w, "Created a subscription with exactly once delivery enabled: %v\n", sub)
	return nil
}

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Pub/Sub.

import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.ProjectTopicName;
import com.google.pubsub.v1.Subscription;
import java.io.IOException;

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

    createSubscriptionWithExactlyOnceDeliveryExample(projectId, topicId, subscriptionId);
  }

  public static void createSubscriptionWithExactlyOnceDeliveryExample(
      String projectId, String topicId, String subscriptionId) throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {

      ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);

      Subscription subscription =
          subscriptionAdminClient.createSubscription(
              Subscription.newBuilder()
                  .setName(subscriptionName.toString())
                  .setTopic(topicName.toString())
                  // Enable exactly once delivery in the subscription.
                  .setEnableExactlyOnceDelivery(true)
                  .build());

      System.out.println(
          "Created a subscription with exactly once delivery enabled: "
              + subscription.getAllFields());
    }
  }
}

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi Pub/Sub Python API.

from google.cloud import pubsub_v1

# TODO(developer): Choose an existing topic.
# project_id = "your-project-id"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"

publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
topic_path = publisher.topic_path(project_id, topic_id)
subscription_path = subscriber.subscription_path(project_id, subscription_id)

with subscriber:
    subscription = subscriber.create_subscription(
        request={
            "name": subscription_path,
            "topic": topic_path,
            "enable_exactly_once_delivery": True,
        }
    )
    print(
        f"Created subscription with exactly once delivery enabled: {subscription}"
    )

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Pub/Sub.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function createSubscriptionWithExactlyOnceDelivery(
  topicNameOrId,
  subscriptionNameOrId,
) {
  // Creates a new subscription
  await pubSubClient
    .topic(topicNameOrId)
    .createSubscription(subscriptionNameOrId, {
      enableExactlyOnceDelivery: true,
    });
  console.log(
    `Created subscription ${subscriptionNameOrId} with exactly-once delivery.`,
  );
  console.log(
    'To process messages, remember to check the return value of ackWithResponse().',
  );
}

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Pub/Sub.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

// Imports the Google Cloud client library
import {PubSub} from '@google-cloud/pubsub';

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function createSubscriptionWithExactlyOnceDelivery(
  topicNameOrId: string,
  subscriptionNameOrId: string,
) {
  // Creates a new subscription
  await pubSubClient
    .topic(topicNameOrId)
    .createSubscription(subscriptionNameOrId, {
      enableExactlyOnceDelivery: true,
    });
  console.log(
    `Created subscription ${subscriptionNameOrId} with exactly-once delivery.`,
  );
  console.log(
    'To process messages, remember to check the return value of ackWithResponse().',
  );
}

Ruby

Contoh berikut menggunakan library klien Pub/Sub Ruby v3. Jika Anda masih menggunakan library v2, lihat panduan migrasi ke v3. Untuk melihat daftar contoh kode Ruby v2, lihat contoh kode yang tidak digunakan lagi.

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Ruby di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi Pub/Sub Ruby API.

# project_id = "your-project-id"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"

pubsub = Google::Cloud::PubSub.new project_id: project_id
subscription_admin = pubsub.subscription_admin

subscription = subscription_admin.create_subscription \
  name: pubsub.subscription_path(subscription_id),
  topic: pubsub.topic_path(topic_id),
  enable_exactly_once_delivery: true

puts "Created subscription with exactly once delivery enabled: " \
     "#{subscription_id}"

PHP

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan PHP di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API PHP Pub/Sub.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub subscription with `Exactly Once Delivery` enabled.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function create_subscription_with_exactly_once_delivery(
    string $projectId,
    string $topicName,
    string $subscriptionName
): void {
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $subscription = $topic->subscription($subscriptionName);
    $subscription->create([
        'enableExactlyOnceDelivery' => true
    ]);

    // Exactly Once Delivery status for the subscription
    $status = $subscription->info()['enableExactlyOnceDelivery'];

    printf('Subscription created with exactly once delivery status: %s' . PHP_EOL, $status ? 'true' : 'false');
}

Rust

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Rust di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Rust Pub/Sub.

use google_cloud_pubsub::client::SubscriptionAdmin;

pub async fn sample(
    client: &SubscriptionAdmin,
    project_id: &str,
    topic_id: &str,
    subscription_id: &str,
) -> anyhow::Result<()> {
    let subscription_name = format!("projects/{project_id}/subscriptions/{subscription_id}");
    let topic_name = format!("projects/{project_id}/topics/{topic_id}");

    let subscription = client
        .create_subscription()
        .set_name(subscription_name)
        .set_topic(topic_name)
        .set_enable_exactly_once_delivery(true)
        .send()
        .await?;

    println!("successfully created subscription {subscription:?}");
    Ok(())
}

Berlangganan dengan pengiriman tepat satu kali

Contoh berikut menunjukkan cara menerima pesan dari langganan dengan pengiriman tepat satu kali yang diaktifkan.

C++

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C++ di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C++ Pub/Sub.

namespace pubsub = ::google::cloud::pubsub;
auto sample = [](pubsub::Subscriber subscriber) {
  return subscriber.Subscribe(
      [&](pubsub::Message const& m, pubsub::ExactlyOnceAckHandler h) {
        std::cout << "Received message " << m << "\n";
        std::move(h).ack().then([id = m.message_id()](auto f) {
          auto status = f.get();
          std::cout << "Message id " << id
                    << " ack() completed with status=" << status << "\n";
        });
        PleaseIgnoreThisSimplifiesTestingTheSamples();
      });
};

C#

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C# di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C# Pub/Sub.


using Google.Cloud.PubSub.V1;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using static Google.Cloud.PubSub.V1.SubscriberClient;

public class ExactlyOnceDeliverySubscriberAsyncSample
{
    public async Task<IEnumerable<string>> ExactlyOnceDeliverySubscriberAsync(string projectId, string subscriptionId)
    {
        // subscriptionId should be the ID of an exactly-once delivery subscription.
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        SubscriberClientBuilder builder = new SubscriberClientBuilder()
        {
            SubscriptionName = subscriptionName,
            Endpoint = "us-west1-pubsub.googleapis.com:443"
        };
        SubscriberClient subscriber = await builder.BuildAsync();
        // To get the status of ACKnowledge (ACK) or Not ACKnowledge (NACK) request in exactly once delivery subscriptions,
        // create a subscription handler that inherits from Google.Cloud.PubSub.V1.SubscriptionHandler. 
        // For more information see Google.Cloud.PubSub.V1.SubscriptionHandler reference docs here:
        // https://cloud.google.com/dotnet/docs/reference/Google.Cloud.PubSub.V1/latest/Google.Cloud.PubSub.V1.SubscriptionHandler
        var subscriptionHandler = new SampleSubscriptionHandler();
        Task subscriptionTask = subscriber.StartAsync(subscriptionHandler);
        // The subscriber will be running until it is stopped.
        await Task.Delay(5000);
        await subscriber.StopAsync(CancellationToken.None);
        // Let's make sure that the start task finished successfully after the call to stop.
        await subscriptionTask;
        return subscriptionHandler.SuccessfulAckedIds;
    }

    // Sample handler to handle messages and ACK/NACK responses.
    public class SampleSubscriptionHandler : SubscriptionHandler
    {
        public ConcurrentBag<string> SuccessfulAckedIds { get; } = new ConcurrentBag<string>();

        /// <summary>
        /// The function that processes received messages. It should be thread-safe.
        /// Return <see cref="Reply.Ack"/> to ACKnowledge the message (meaning it won't be received again).
        /// Return <see cref="Reply.Nack"/> to Not ACKnowledge the message (meaning it will be received again).
        /// From the point of view of message acknowledgement, throwing an exception is equivalent to returning <see cref="Reply.Nack"/>.
        /// </summary>
        public override async Task<Reply> HandleMessage(PubsubMessage message, CancellationToken cancellationToken)
        {
            string text = message.Data.ToStringUtf8();
            Console.WriteLine($"Message {message.MessageId}: {text}");
            return await Task.FromResult(Reply.Ack);
        }

        /// <summary>
        /// This method will receive responses for all acknowledge requests.
        /// </summary>
        public override void HandleAckResponses(IReadOnlyList<AckNackResponse> responses)
        {
            foreach (var response in responses)
            {
                if (response.Status == AcknowledgementStatus.Success)
                {
                    SuccessfulAckedIds.Add(response.MessageId);
                }

                string result = response.Status switch
                {
                    AcknowledgementStatus.Success => $"MessageId {response.MessageId} successfully acknowledged.",
                    AcknowledgementStatus.PermissionDenied => $"MessageId {response.MessageId} failed to acknowledge due to a permission denied error.",
                    AcknowledgementStatus.FailedPrecondition => $"MessageId {response.MessageId} failed to acknowledge due to a failed precondition.",
                    AcknowledgementStatus.InvalidAckId => $"MessageId {response.MessageId} failed to acknowledge due an invalid or expired AckId.",
                    AcknowledgementStatus.Other => $"MessageId {response.MessageId} failed to acknowledge due to an unknown reason.",
                    _ => $"Unknown acknowledgement status for messageId {response.MessageId}."
                };

                Console.WriteLine(result);
            }
        }
    }
}

Go

Contoh berikut menggunakan versi utama library klien Pub/Sub Go (v2). Jika Anda masih menggunakan library v1, lihat panduan migrasi ke v2. Untuk melihat daftar contoh kode v1, lihat contoh kode yang tidak digunakan lagi.

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Pub/Sub.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/pubsub/v2"
	"google.golang.org/api/option"
)

// receiveMessagesWithExactlyOnceDeliveryEnabled instantiates a subscriber client.
// This differs from regular subscribing since you must call msg.AckWithResult()
// or msg.NackWithResult() instead of the regular Ack/Nack methods.
// When exactly once delivery is enabled on the subscription, the message is
// guaranteed to not be delivered again if the ack result succeeds.
func receiveMessagesWithExactlyOnceDeliveryEnabled(w io.Writer, projectID, subID string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()

	// Pub/Sub's exactly once delivery guarantee only applies when subscribers connect to the service in the same region.
	// For list of locational endpoints for Pub/Sub, see https://cloud.google.com/pubsub/docs/reference/service_apis_overview#list_of_locational_endpoints
	client, err := pubsub.NewClient(ctx, projectID, option.WithEndpoint("us-west1-pubsub.googleapis.com:443"))
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	// client.Subscriber can be passed a subscription ID (e.g. "my-sub") or
	// a fully qualified name (e.g. "projects/my-project/subscriptions/my-sub").
	// If a subscription ID is provided, the project ID from the client is used.
	sub := client.Subscriber(subID)
	// Set MinDurationPerAckExtension high to avoid any unintentional
	// acknowledgment expirations (e.g. due to network events).
	// This can lead to high tail latency in case of client crashes.
	sub.ReceiveSettings.MinDurationPerAckExtension = 600 * time.Second

	// Receive messages for 10 seconds, which simplifies testing.
	// Comment this out in production, since `Receive` should
	// be used as a long running operation.
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()
	err = sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) {
		fmt.Fprintf(w, "Got message: %q\n", string(msg.Data))
		r := msg.AckWithResult()
		// Block until the result is returned and a pubsub.AcknowledgeStatus
		// is returned for the acked message.
		status, err := r.Get(ctx)
		if err != nil {
			fmt.Fprintf(w, "MessageID: %s failed when calling result.Get: %v", msg.ID, err)
		}

		switch status {
		case pubsub.AcknowledgeStatusSuccess:
			fmt.Fprintf(w, "Message successfully acked: %s", msg.ID)
		case pubsub.AcknowledgeStatusInvalidAckID:
			fmt.Fprintf(w, "Message failed to ack with response of Invalid. ID: %s", msg.ID)
		case pubsub.AcknowledgeStatusPermissionDenied:
			fmt.Fprintf(w, "Message failed to ack with response of Permission Denied. ID: %s", msg.ID)
		case pubsub.AcknowledgeStatusFailedPrecondition:
			fmt.Fprintf(w, "Message failed to ack with response of Failed Precondition. ID: %s", msg.ID)
		case pubsub.AcknowledgeStatusOther:
			fmt.Fprintf(w, "Message failed to ack with response of Other. ID: %s", msg.ID)
		default:
		}
	})
	if err != nil {
		return fmt.Errorf("got err from sub.Receive: %w", err)
	}
	return nil
}

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Pub/Sub.


import com.google.cloud.pubsub.v1.AckReplyConsumerWithResponse;
import com.google.cloud.pubsub.v1.AckResponse;
import com.google.cloud.pubsub.v1.MessageReceiverWithAckResponse;
import com.google.cloud.pubsub.v1.Subscriber;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.PubsubMessage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class SubscribeWithExactlyOnceConsumerWithResponseExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";

    subscribeWithExactlyOnceConsumerWithResponseExample(projectId, subscriptionId);
  }

  public static void subscribeWithExactlyOnceConsumerWithResponseExample(
      String projectId, String subscriptionId) {
    ProjectSubscriptionName subscriptionName =
        ProjectSubscriptionName.of(projectId, subscriptionId);

    // Instantiate an asynchronous message receiver using `AckReplyConsumerWithResponse`
    // instead of `AckReplyConsumer` to get a future that tracks the result of the ack call.
    // When exactly once delivery is enabled on the subscription, the message is guaranteed
    // to not be delivered again if the ack future succeeds.
    MessageReceiverWithAckResponse receiverWithResponse =
        (PubsubMessage message, AckReplyConsumerWithResponse consumerWithResponse) -> {
          try {
            // Handle incoming message, then ack the message, and receive an ack response.
            System.out.println("Message received: " + message.getData().toStringUtf8());
            Future<AckResponse> ackResponseFuture = consumerWithResponse.ack();

            // Retrieve the completed future for the ack response from the server.
            AckResponse ackResponse = ackResponseFuture.get();

            switch (ackResponse) {
              case SUCCESSFUL:
                // Success code means that this MessageID will not be delivered again.
                System.out.println("Message successfully acked: " + message.getMessageId());
                break;
              case INVALID:
                System.out.println(
                    "Message failed to ack with a response of Invalid. Id: "
                        + message.getMessageId());
                break;
              case PERMISSION_DENIED:
                System.out.println(
                    "Message failed to ack with a response of Permission Denied. Id: "
                        + message.getMessageId());
                break;
              case FAILED_PRECONDITION:
                System.out.println(
                    "Message failed to ack with a response of Failed Precondition. Id: "
                        + message.getMessageId());
                break;
              case OTHER:
                System.out.println(
                    "Message failed to ack with a response of Other. Id: "
                        + message.getMessageId());
                break;
              default:
                break;
            }
          } catch (InterruptedException | ExecutionException e) {
            System.out.println(
                "MessageId: " + message.getMessageId() + " failed when retrieving future");
          } catch (Throwable t) {
            System.out.println("Throwable caught" + t.getMessage());
          }
        };

    Subscriber subscriber = null;
    try {
      // Pub/Sub's exactly once delivery guarantee only applies when subscribers connect to the
      // service in the same region.
      // For list of locational endpoints for Pub/Sub, see
      // https://cloud.google.com/pubsub/docs/reference/service_apis_overview#list_of_locational_endpoints
      subscriber =
          Subscriber.newBuilder(subscriptionName, receiverWithResponse)
              .setEndpoint("us-west1-pubsub.googleapis.com:443")
              .build();
      // Start the subscriber.
      subscriber.startAsync().awaitRunning();
      System.out.printf("Listening for messages on %s:\n", subscriptionName.toString());
      // Allow the subscriber to run for 30s unless an unrecoverable error occurs.
      subscriber.awaitTerminated(30, TimeUnit.SECONDS);
    } catch (TimeoutException timeoutException) {
      // Shut down the subscriber after 30s. Stop receiving messages.
      subscriber.stopAsync();
    }
  }
}

PHP

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan PHP di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API PHP Pub/Sub.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Subscribe and pull messages from a subscription
 * with `Exactly Once Delivery` enabled.
 *
 * @param string $projectId
 * @param string $subscriptionId
 */
function subscribe_exactly_once_delivery(
    string $projectId,
    string $subscriptionId
): void {
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
        // use the apiEndpoint option to set a regional endpoint
        'apiEndpoint' => 'us-west1-pubsub.googleapis.com:443'
    ]);

    $subscription = $pubsub->subscription($subscriptionId);
    $messages = $subscription->pull();

    foreach ($messages as $message) {
        // When exactly once delivery is enabled on the subscription,
        // the message is guaranteed to not be delivered again if the ack succeeds.
        // Passing the `returnFailures` flag retries any temporary failures received
        // while acking the msg and also returns any permanently failed msgs.
        // Passing this flag on a subscription with exactly once delivery disabled
        // will always return an empty array.
        $failedMsgs = $subscription->acknowledge($message, ['returnFailures' => true]);

        if (empty($failedMsgs)) {
            printf('Acknowledged message: %s' . PHP_EOL, $message->data());
        } else {
            // Either log or store the $failedMsgs to be retried later
        }
    }
}

Ruby

Contoh berikut menggunakan library klien Pub/Sub Ruby v3. Jika Anda masih menggunakan library v2, lihat panduan migrasi ke v3. Untuk melihat daftar contoh kode Ruby v2, lihat contoh kode yang tidak digunakan lagi.

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Ruby di Panduan Memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi Pub/Sub Ruby API.

# project_id = "your-project-id"
# subscription_id = "your-subscription-id"
pubsub = Google::Cloud::Pubsub.new \
  project_id: project_id,
  endpoint: "us-west1-pubsub.googleapis.com:443"
subscriber = pubsub.subscriber subscription_id

listener = subscriber.listen do |received_message|
  puts "Received message: #{received_message.data}"
  # Pass in callback to access the acknowledge result.
  # For subscription with Exactly once delivery disabled the result will be
  # success always.
  received_message.acknowledge! do |result|
    puts "Acknowledge result's status: #{result.status}"
  end
end

listener.start
# Let the main thread sleep for 60 seconds so the thread for listening
# messages does not quit
sleep 60
listener.stop.wait!

Rust

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Rust di Panduan memulai: Menggunakan Library Klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Rust Pub/Sub.

use google_cloud_pubsub::client::Subscriber;
use google_cloud_pubsub::subscriber::handler::Handler;
use std::time::Duration;

pub async fn sample(project_id: &str, subscription_id: &str) -> anyhow::Result<()> {
    let subscription_name = format!("projects/{project_id}/subscriptions/{subscription_id}");
    let client = Subscriber::builder().build().await?;
    let mut stream = client.subscribe(subscription_name).build();

    // Terminate the example after 10 seconds.
    let shutdown_token = stream.shutdown_token();
    let shutdown = tokio::spawn(async move {
        tokio::time::sleep(Duration::from_secs(10)).await;
        shutdown_token.shutdown().await;
    });

    let mut tasks = Vec::new();
    println!("Listening for messages...");
    while let Some((m, Handler::ExactlyOnce(h))) = stream.next().await.transpose()? {
        println!("Received message: {m:?}");
        tasks.push(tokio::spawn(async move {
            // We spawn a background task so that receiving the next message
            // is not blocked on the server confirming the ack for this
            // message.
            //
            // You might choose to use a work queue in your application.
            match h.confirmed_ack().await {
                Ok(()) => println!(
                    "Confirmed ack for message={m:?}. The message will not be redelivered."
                ),
                Err(e) => println!("Failed to confirm ack for message={m:?} with error={e:?}"),
            }
        }));
    }
    shutdown.await?;
    println!("Done listening for messages");

    for t in tasks {
        t.await?;
    }
    println!("Done acking messages");

    Ok(())
}

Memantau langganan pengiriman tepat satu kali

Metrik subscription/exactly_once_warning_count mencatat jumlah peristiwa yang dapat menyebabkan kemungkinan pengiriman ulang (valid atau duplikat). Metrik ini menghitung berapa kali Pub/Sub gagal memproses permintaan yang terkait dengan ID konfirmasi (permintaan ModifyAckDeadline atau acknowledgment). Alasan kegagalan dapat disebabkan oleh server atau klien. Misalnya, jika lapisan persistensi yang digunakan untuk mempertahankan informasi pengiriman tepat satu kali tidak tersedia, hal ini akan menjadi peristiwa berbasis server. Jika klien mencoba mengonfirmasi pesan dengan ID konfirmasi yang tidak valid, hal ini akan menjadi peristiwa berbasis klien.

subscription/exactly_once_warning_count menangkap peristiwa yang mungkin atau mungkin tidak menyebabkan pengiriman ulang yang sebenarnya dan dapat menimbulkan derau berdasarkan perilaku klien. Misalnya: permintaan acknowledgment atau ModifyAckDeadline berulang dengan ID konfirmasi yang tidak valid akan meningkatkan metrik berulang kali.

Metrik berikut juga berguna untuk memahami perilaku klien:

  • Metrik subscription/expired_ack_deadlines_count menunjukkan jumlah masa berlaku ID konfirmasi. Masa berlaku ID konfirmasi yang habis dapat menyebabkan kegagalan untuk permintaan ModifyAckDeadline dan acknowledgment.

  • Metrik service.serviceruntime.googleapis.com/api/request_count dapat digunakan untuk menangkap kegagalan permintaan ModifyAckDeadline atau acknowledgment dalam kasus saat permintaan mencapai Google Cloud tetapi tidak mencapai Pub/Sub. Ada kegagalan yang tidak akan dicatat oleh metrik ini—misalnya, saat klien terputus dari Google Cloud.

Pada sebagian besar kasus peristiwa kegagalan yang dapat dicoba ulang, library klien yang didukung akan otomatis mencoba ulang permintaan.

Kuota

Langganan pengiriman tepat satu kali tunduk pada persyaratan kuota tambahan. Kuota ini diterapkan pada:

  • Jumlah pesan yang digunakan dari langganan dengan pengiriman tepat satu kali yang diaktifkan per region.
  • Jumlah pesan yang dikonfirmasi atau yang batas waktunya diperpanjang saat menggunakan langganan dengan pengiriman tepat satu kali yang diaktifkan per region.

Untuk mengetahui informasi selengkapnya tentang kuota ini, lihat tabel di topik Kuota.

Pengiriman tepat satu kali dan langganan yang diurutkan

Pub/Sub mendukung pengiriman tepat satu kali dengan pengiriman berurutan.

Saat menggunakan pengurutan dengan pengiriman tepat satu kali, Pub/Sub mengharapkan konfirmasi sesuai urutan. Jika konfirmasi tidak berurutan, layanan akan menggagalkan permintaan dengan error sementara. Jika batas waktu konfirmasi berakhir sebelum konfirmasi berurutan untuk pengiriman, klien akan menerima pengiriman ulang pesan. Oleh karena itu, saat Anda menggunakan pengurutan dengan pengiriman tepat satu kali, throughput klien dibatasi hingga ribuan pesan per detik.

Pengiriman tepat satu kali dan langganan push

Pub/Sub mendukung pengiriman tepat satu kali hanya dengan langganan pull.

Klien yang menggunakan pesan dari langganan push mengonfirmasi pesan dengan merespons permintaan push dengan respons yang berhasil. Namun, klien tidak tahu apakah langganan Pub/Sub menerima respons dan memprosesnya. Hal ini berbeda dengan langganan pull, di mana permintaan konfirmasi dimulai oleh klien dan langganan Pub/Sub merespons jika permintaan berhasil diproses. Oleh karena itu, semantik pengiriman tepat satu kali tidak cocok dengan langganan push.

Yang perlu diketahui

  • Jika batas waktu konfirmasi tidak ditentukan pada waktu CreateSubscription, langganan yang mengaktifkan pengiriman tepat satu kali akan memiliki batas waktu konfirmasi default 60 detik.

  • Batas waktu konfirmasi default yang lebih lama bermanfaat untuk menghindari pengiriman ulang yang disebabkan oleh peristiwa jaringan. Library klien yang didukung tidak menggunakan batas waktu konfirmasi langganan default.

  • Langganan pengiriman tepat satu kali memiliki latensi publikasi ke langganan yang jauh lebih tinggi dibandingkan dengan langganan reguler.

  • Jika Anda memerlukan throughput tinggi, klien pengiriman tepat satu kali Anda juga harus menggunakan penarikan streaming.

  • Langganan mungkin menerima beberapa salinan pesan yang sama karena duplikat sisi publikasi, meskipun pengiriman tepat satu kali diaktifkan. Duplikat sisi publikasi dapat disebabkan oleh beberapa percobaan ulang publikasi unik oleh klien publikasi atau layanan Pub/Sub. Beberapa publikasi unik oleh klien publikasi, di seluruh percobaan ulang, menyebabkan pengiriman ulang dengan ID pesan yang berbeda. Beberapa publikasi unik oleh layanan Pub/Sub, untuk merespons permintaan publikasi klien, menyebabkan pengiriman ulang dengan ID pesan yang sama.

  • Anda dapat mencoba kembali kegagalan di subscription/exactly_once_warning_count dan library klien yang didukung akan mencoba kembali secara otomatis. Namun, kegagalan yang terkait dengan ID konfirmasi yang tidak valid tidak dapat dicoba lagi.