更新訂閱項目

更新訂閱項目。

深入探索

如需包含這個程式碼範例的詳細說明文件,請參閱下列文章:

程式碼範例

C++

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

如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

namespace pubsub_admin = ::google::cloud::pubsub_admin;
namespace pubsub = ::google::cloud::pubsub;
[](pubsub_admin::SubscriptionAdminClient client,
   std::string const& project_id, std::string const& subscription_id,
   std::string const& endpoint) {
  google::pubsub::v1::ModifyPushConfigRequest request;
  request.set_subscription(
      pubsub::Subscription(project_id, subscription_id).FullName());
  request.mutable_push_config()->set_push_endpoint(endpoint);
  auto status = client.ModifyPushConfig(request);
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The subscription push configuration was successfully"
            << " modified\n";
}

C#

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

如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


using Google.Cloud.PubSub.V1;

public class UpdatePushConfigurationSample
{
    public void UpdatePushConfiguration(string projectId, string subscriptionId, string pushEndpoint)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        PushConfig pushConfig = new PushConfig { PushEndpoint = pushEndpoint };

        subscriber.ModifyPushConfig(subscriptionName, pushConfig);
    }
}

Go

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

如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub/v2"
	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

func updateEndpoint(w io.Writer, projectID, subscriptionName, endpoint string) error {
	// projectID := "my-project-id"
	// subscriptionName := "projects/my-project/subscriptions/my-sub"
	// endpoint := "https://my-test-project.appspot.com/push"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	req := &pubsubpb.UpdateSubscriptionRequest{
		Subscription: &pubsubpb.Subscription{
			Name: subscriptionName,
			PushConfig: &pubsubpb.PushConfig{
				PushEndpoint: endpoint,
			},
		},
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{"push_config"},
		},
	}
	subConfig, err := client.SubscriptionAdminClient.UpdateSubscription(ctx, req)
	if err != nil {
		return fmt.Errorf("Update: %w", err)
	}
	fmt.Fprintf(w, "Updated subscription config: %v\n", subConfig)
	return nil
}

Java

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

如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.protobuf.FieldMask;
import com.google.pubsub.v1.Subscription;
import com.google.pubsub.v1.SubscriptionName;
import com.google.pubsub.v1.UpdateSubscriptionRequest;

public class UpdateSubscription {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project_id";
    String subscriptionId = "example-subscription_id";
    updateSubscription(projectId, subscriptionId);
  }

  public static void updateSubscription(String projectId, String subscriptionId) throws Exception {
    try (SubscriptionAdminClient client = SubscriptionAdminClient.create()) {
      FieldMask updateMask = FieldMask.newBuilder().addPaths("labels").build();
      Subscription subscription =
          Subscription.newBuilder()
              .setName(SubscriptionName.of(projectId, subscriptionId).toString())
              .putLabels("env", "test")
              .build();

      UpdateSubscriptionRequest request =
          UpdateSubscriptionRequest.newBuilder()
              .setSubscription(subscription)
              .setUpdateMask(updateMask)
              .build();

      Subscription response = client.updateSubscription(request);
      System.out.println("Updated subscription: " + response.getName());
      System.out.println("Labels: " + response.getLabelsMap());
    }
  }
}

Node.js

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

如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

'use strict';

const {SubscriberClient} = require('@google-cloud/pubsub-api');
const {status} = require('@grpc/grpc-js');

const client = new SubscriberClient();

/**
 * Use the updateSubscription method
 *
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} subscriptionId - The ID of the Pub/Sub subscription to update.
 */
async function updateSubscription(projectId, subscriptionId) {
  try {
    const subscription = {
      name: `projects/${projectId}/subscriptions/${subscriptionId}`,
      labels: {
        env: 'test',
      },
    };
    const updateMask = {
      paths: ['labels'],
    };

    const request = {
      subscription,
      updateMask,
    };

    const [response] = await client.updateSubscription(request);
    console.log(`Updated subscription: ${response.name}`);
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Subscription not found: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument provided: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { updateSubscription };

Python

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

如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

import google.api_core.exceptions
from google.cloud import pubsub_v1
from google.protobuf import field_mask_pb2

client = pubsub_v1.SubscriberClient()


def update_subscription(project_id: str, subscription_id: str) -> None:
    """Use the update_subscription method

    Args:
        project_id: The Google Cloud project ID.
        subscription_id: The ID of the existing Pub/Sub subscription to update
            (caller-specified or server-generated when created). Must start with a
            letter, contain 3-255 characters (letters, numbers, dashes, underscores,
            periods, tildes, plus, or percent signs), and not start with 'goog'.
    """
    subscription_path = client.subscription_path(project_id, subscription_id)
    subscription = pubsub_v1.types.Subscription(
        name=subscription_path,
        labels={"env": "test"},
    )
    update_mask = field_mask_pb2.FieldMask(paths=["labels"])

    try:
        response = client.update_subscription(
            subscription=subscription,
            update_mask=update_mask,
        )
        print(f"Updated subscription: {response.name}")
        print(f"Labels: {response.labels}")
    except google.api_core.exceptions.GoogleAPICallError as exc:
        print(f"Failed to update subscription: {exc}")

Ruby

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

如要向 Pub/Sub 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

# subscription_id   = "your-subscription-id"
# new_endpoint      = "Endpoint where your app receives messages""

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

subscription = subscription_admin.get_subscription \
  subscription: pubsub.subscription_path(subscription_id)
subscription.push_config = Google::Cloud::PubSub::V1::PushConfig.new \
  push_endpoint: new_endpoint

subscription_admin.update_subscription subscription: subscription,
                                       update_mask: {
                                         paths: ["push_config"]
                                       }

puts "Push endpoint updated."

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽工具。