僅傳送一次

本頁面說明如何使用 Pub/Sub 的「僅一次」功能接收及確認訊息,以便追蹤及避免重複處理訊息。啟用這項功能後,Pub/Sub 會提供下列語意:

  • 訂閱者可以判斷訊息確認是否成功。

  • 成功確認訊息後,系統不會重新傳送訊息。

  • 訊息未處理完畢前,不會重新傳送。在確認期限到期或訊息獲得確認之前,訊息都會視為未完成。

  • 如果因確認期限到期或用戶端發起否定確認,而導致多次有效傳送,則只能使用最新的確認 ID 確認訊息。使用先前確認 ID 的要求都會失敗。

啟用僅限一次功能後,訂閱者可以遵循下列指南,確保訊息只會處理一次:

  • 在確認期限內確認訊息。

  • 維護訊息處理進度的相關資訊,直到訊息成功確認為止。

  • 使用訊息處理進度的相關資訊,避免在確認失敗時重複工作。

只有提取訂閱項目類型支援僅傳送一次,包括使用 StreamingPull API 的訂閱者。推送和匯出訂閱項目不支援「僅傳送一次」功能。

Pub/Sub 支援在雲端區域內僅傳送一次訊息,依據的是 Pub/Sub 定義的專屬訊息 ID。

重新提交與重複提交

請務必瞭解預期和非預期重新傳送之間的差異。

  • 如果用戶端對訊息發出負面確認,或未在訊息確認期限到期前延長期限,系統就會重新傳送訊息。重新傳送視為有效,系統運作正常。

    如要排解重新傳送的問題,請參閱「處理重複項目」。

  • 重複訊息是指在成功確認後,或確認期限到期前重新傳送的訊息。

  • 重新傳送的訊息在重新傳送嘗試之間會保留相同的訊息 ID。

啟用「僅傳送一次」的訂閱項目不會收到重複的訊息。

用戶端程式庫支援「僅傳送一次」

  • 支援的用戶端程式庫具有確認介面,可提供回應 (例如:Go)。您可以使用這個介面,確認確認要求是否成功。如果確認要求成功,用戶端就不會收到重新傳送的訊息。如果確認要求失敗,用戶端會預期重新傳送。

  • 用戶端也可以使用支援的用戶端程式庫,而不使用確認介面。不過,在這種情況下,確認失敗可能會導致訊息在不通知的情況下重新傳送。

  • 支援的用戶端程式庫提供設定最短租約延長時間的介面 (例如 Go)。您必須將租約展延下限設為較高的值,以免發生任何與網路相關的確認逾期。最大值為 600 秒。

  • 如果您使用 Java 用戶端程式庫,並使用 setChannelProvider() 方法,透過自訂 gRPC 管道初始化訂閱者,建議您在建構 TransportChannelProvider 時,也將 maxInboundMetadataSize 設為至少 1 MB。如要進行這項設定,您可以使用 InstantiatingGrpcChannelProvider.Builder.setMaxInboundMetadataSize() 或 ManagedChannelBuilder.maxInboundMetadataSize() 方法。

與「僅傳送一次」相關的變數預設值和範圍,以及變數名稱,可能會因用戶端程式庫而異。舉例來說,在 Java 用戶端程式庫中,下列變數會控制精確一次傳遞。

變數 說明 值
setEnableExactlyOnceDelivery 啟用或停用「僅一次」傳遞。 true 或 false 預設值=false
minDurationPerAckExtension 延長修改確認期限的最短時間 (以秒為單位)。 範圍:0 至 600,預設值:無
maxDurationPerAckExtension 延長確認期限修改時間的時間上限 (以秒為單位)。 範圍:0 至 600,預設值:無

在僅傳送一次的情況下,如果確認 ID 已過期,向 Pub/Sub 提出的 modifyAckDeadline 或 acknowledgment 要求就會失敗。在這種情況下,服務會將過期的確認 ID 視為無效,因為可能已有較新的傳送作業正在進行。這是為了確保訊息只傳送一次。接著,您會看到 acknowledgment 和 ModifyAckDeadline 要求傳回 INVALID_ARGUMENT 回應。如果停用「僅傳送一次」功能,當確認 ID 過期時,這些要求會傳回 OK。

為確保 acknowledgment 和 ModifyAckDeadline 要求具有有效的確認 ID,建議您將 minDurationPerAckExtension 的值設為較高的數字。

區域性考量

只有在訂閱者連線至相同區域的服務時,才能保證僅傳送一次。如果訂閱者應用程式分散在多個區域,即使啟用「僅傳送一次」功能,也可能導致重複傳送訊息。發布者可以將訊息傳送至任何區域,且仍能保證僅傳送一次。

在 Cloud de Confiance中執行應用程式時,系統預設會連線至相同區域的 Pub/Sub 端點。因此,在 Cloud de Confiance中的單一區域內執行應用程式,通常可確保您與單一區域互動。

如果訂閱者應用程式在 Cloud de Confiance以外或多個區域執行,您可以在設定 Pub/Sub 用戶端時使用位置端點,確保連線至單一區域。Pub/Sub 的所有位置端點都指向單一區域。如要進一步瞭解位置端點,請參閱「Pub/Sub 端點」。如需 Pub/Sub 所有位置端點的清單,請參閱「位置端點清單」。

建立「僅傳送一次」的訂閱項目

您可以使用 Cloud de Confiance 控制台、Google Cloud CLI、用戶端程式庫或 Pub/Sub API,建立僅傳送一次的訂閱項目。

控制台

如要建立僅傳送一次的提取訂閱項目,請按照下列步驟操作:

  1. 前往 Cloud de Confiance 控制台的「Subscriptions」(訂閱項目) 頁面。

    前往「訂閱項目」頁面

  2. 按一下「Create Subscription」 (建立訂閱項目)。

  3. 輸入訂閱 ID。

  4. 從下拉式選單中選擇或建立主題。

    訂閱項目會接收主題中的訊息。

  5. 在「僅傳送一次」部分,選取「啟用僅傳送一次」。

  6. 點選「建立」。

gcloud

如要建立僅傳送一次的提取訂閱項目,請使用 gcloud pubsub subscriptions create 指令並加上 --enable-exactly-once-delivery 旗標:

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

更改下列內容:

  • SUBSCRIPTION_ID:要建立的訂閱項目 ID
  • TOPIC_ID:要附加至訂閱項目的主題 ID

REST

如要建立僅傳送一次的訂閱項目,請使用 projects.subscriptions.create 方法。

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

更改下列內容:

  • PROJECT_ID:要在當中建立訂閱項目的專案 ID
  • SUBSCRIPTION_ID:要建立的訂閱項目 ID

如要建立僅傳送一次的提取訂閱項目,請在要求主體中指定下列內容:

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

更改下列內容:

  • PROJECT_ID:主題所在專案的專案 ID
  • TOPIC_ID:要附加至訂閱項目的主題 ID

C++

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 C++ 設定操作說明進行操作。詳情請參閱 Pub/Sub C++ API 參考文件。

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#

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 C# 設定操作說明進行操作。詳情請參閱 Pub/Sub C# API 參考文件。


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

下列範例使用 Go Pub/Sub 用戶端程式庫的主要版本 (v2)。如果您仍在使用第 1 版程式庫,請參閱第 2 版遷移指南。如要查看第 1 版程式碼範例清單,請參閱已淘汰的程式碼範例。

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Go 設定操作說明進行操作。詳情請參閱 Pub/Sub Go API 參考文件。

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

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Java 設定操作說明進行操作。詳情請參閱 Pub/Sub Java API 參考文件。

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

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Python 設定操作說明進行操作。詳情請參閱 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

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Node.js 設定操作說明進行操作。詳情請參閱 Pub/Sub Node.js API 參考文件。

/**
 * 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

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Node.js 設定操作說明進行操作。詳情請參閱 Pub/Sub Node.js API 參考文件。

/**
 * 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 Pub/Sub 用戶端程式庫 v3。如果您仍在使用第 2 版程式庫,請參閱第 3 版遷移指南。如要查看 Ruby v2 程式碼範例清單,請參閱已淘汰的程式碼範例。

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Ruby 設定操作說明進行操作。詳情請參閱 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

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 PHP 設定操作說明進行操作。詳情請參閱 Pub/Sub PHP API 參考文件。

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

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Rust 設定操作說明進行操作。詳情請參閱 Pub/Sub Rust API 參考文件。

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(())
}

訂閱並啟用「僅傳送一次」

以下範例說明如何從已啟用「僅傳送一次」功能的訂閱項目接收訊息。

C++

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 C++ 設定操作說明進行操作。詳情請參閱 Pub/Sub C++ API 參考文件。

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#

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 C# 設定操作說明進行操作。詳情請參閱 Pub/Sub C# API 參考文件。


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

下列範例使用 Go Pub/Sub 用戶端程式庫的主要版本 (v2)。如果您仍在使用第 1 版程式庫,請參閱第 2 版遷移指南。如要查看第 1 版程式碼範例清單,請參閱已淘汰的程式碼範例。

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Go 設定操作說明進行操作。詳情請參閱 Pub/Sub Go API 參考文件。

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

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Java 設定操作說明進行操作。詳情請參閱 Pub/Sub Java API 參考文件。


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

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 PHP 設定操作說明進行操作。詳情請參閱 Pub/Sub PHP API 參考文件。

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 Pub/Sub 用戶端程式庫 v3。如果您仍在使用第 2 版程式庫,請參閱第 3 版遷移指南。如要查看 Ruby v2 程式碼範例清單,請參閱已淘汰的程式碼範例。

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Ruby 設定操作說明進行操作。詳情請參閱 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

在試用這個範例之前,請先按照「快速入門導覽課程:使用用戶端程式庫」中的 Rust 設定操作說明進行操作。詳情請參閱 Pub/Sub Rust API 參考文件。

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(())
}

監控「僅傳送一次」訂閱項目

subscription/exactly_once_warning_count 指標會記錄可能導致重新傳送 (有效或重複) 的事件數量。這項指標會計算 Pub/Sub 無法處理與確認 ID 相關聯的要求 (ModifyAckDeadline 或 acknowledgment 要求) 的次數。失敗原因可能與伺服器或用戶端有關。舉例來說,如果用於維護「僅傳送一次」資訊的持續性層無法使用,就會是伺服器端事件。如果用戶端嘗試使用無效的確認 ID 確認訊息,就會是用戶端事件。

subscription/exactly_once_warning_count 會擷取可能或不可能導致實際重新傳送的事件,並可能根據用戶端行為產生雜訊。舉例來說,如果重複傳送 acknowledgment 或 ModifyAckDeadline 要求,且確認 ID 無效,指標就會重複遞增。

下列指標也有助於瞭解用戶端行為:

  • subscription/expired_ack_deadlines_count 指標會顯示確認 ID 到期的次數。確認 ID 到期可能會導致 ModifyAckDeadline 和 acknowledgment 要求失敗。

  • service.serviceruntime.googleapis.com/api/request_count 指標可用於擷取 ModifyAckDeadline 或 acknowledgment 要求的失敗,適用於要求到達 Cloud de Confiance by S3NS 但未到達 Pub/Sub 的情況。這項指標不會擷取某些失敗情形,例如用戶端與 Cloud de Confiance by S3NS中斷連線。

在大多數可重試的失敗事件中,支援的用戶端程式庫會自動重試要求。

配額

「僅傳送一次」訂閱項目須遵守其他配額規定。這些配額會強制套用至:

  • 每個區域中,啟用「僅傳送一次」功能的訂閱項目所使用的訊息數量。
  • 每個區域中,使用已啟用「僅傳送一次」的訂閱項目時,已確認或期限延長的訊息數量。

如要進一步瞭解這些配額,請參閱「配額」主題中的表格。

僅傳送一次和依序訂閱

Pub/Sub 支援依序傳送,可確保僅傳送一次。

使用「僅一次」傳遞機制排序時,Pub/Sub 會預期確認訊息依序傳送。如果確認訊息順序不正確,服務會失敗並傳回暫時性錯誤。如果確認期限在傳送的依序確認前到期,用戶端會收到重新傳送的訊息。因此,當您使用排序功能和僅傳送一次功能時,用戶端處理量會限制在每秒數千則訊息。

「僅傳送一次」和推送訂閱項目

Pub/Sub 僅支援提取訂閱項目的「僅傳送一次」功能。

用戶端從推送訂閱項目接收訊息後,會以成功回應來回覆推送要求,藉此確認訊息。不過,用戶端不知道 Pub/Sub 訂閱項目是否已收到並處理回應。這與提取訂閱項目不同,提取訂閱項目是由用戶端發出確認要求,Pub/Sub 訂閱項目則會在要求處理成功時回應。因此,「僅傳送一次」語意不適用於推送訂閱項目。

注意事項

  • 如果在 CreateSubscription 時未指定確認期限,則啟用「僅傳送一次」的訂閱項目預設確認期限為 60 秒。

  • 較長的預設確認期限有助於避免因網路事件而重新傳送。支援的用戶端程式庫不會使用預設的訂閱項目確認期限。

  • 與一般訂閱項目相比,「僅傳送一次」訂閱項目的發布至訂閱延遲時間明顯較長。

  • 如果您需要高處理量,則僅傳送一次用戶端也必須使用串流提取。

  • 即使啟用「僅傳送一次」,訂閱項目仍可能因發布端重複而收到多個相同訊息副本。發布端重複可能是因為發布用戶端或 Pub/Sub 服務多次嘗試發布。發布用戶端在重試期間多次發布不重複訊息,會導致系統以「不同」訊息 ID 重新傳送訊息。Pub/Sub 服務為回應用戶端發布要求,多次發布不重複訊息,導致系統以「相同」訊息 ID 重新傳送訊息。

  • 您可以在 subscription/exactly_once_warning_count 中重試失敗作業,支援的用戶端程式庫會自動重試這些作業。不過,如果失敗原因與確認 ID 無效有關,則無法重試。