구독 업데이트

구독을 업데이트합니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

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 샘플 브라우저 참조하기