更改订阅类型

创建订阅后,您可以将传送方法更改为推送、拉取或导出。

准备工作

所需的角色和权限

如需获取更改订阅类型并管理它们所需的权限,请让管理员授予您主题或项目的 Pub/Sub Editor (roles/pubsub.editor) IAM 角色。如需详细了解如何授予角色,请参阅管理访问权限

此预定义角色包含更改订阅类型及管理订阅类型所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

需要以下权限才能更改订阅类型并对其进行管理:

  • 从订阅中拉取: pubsub.subscriptions.consume
  • 创建订阅: pubsub.subscriptions.create
  • 删除订阅: pubsub.subscriptions.delete
  • 获取订阅: pubsub.subscriptions.get
  • 列出订阅: pubsub.subscriptions.list
  • 更新订阅: pubsub.subscriptions.update
  • 为主题附加订阅: pubsub.topics.attachSubscription
  • 获取订阅的 IAM 政策: pubsub.subscriptions.getIamPolicy
  • 为订阅配置 IAM 政策 pubsub.subscriptions.setIamPolicy

您也可以使用自定义角色或其他预定义角色来获取这些权限。

您可以在项目级和单个资源级配置访问权限控制。您可以在一个项目中创建订阅,并将其附加到位于其他项目中的主题。确保您拥有每个项目所需的权限。

修改传送方式

您可以在不同的订阅类型之间切换。

控制台

如需修改订阅,请完成以下步骤。

  1. 在 Google Cloud 控制台中,前往订阅页面。

    前往“订阅”页面

  2. 点击要更新的订阅旁边的
  3. 递送类型中,选择递送选项。
  4. 根据需要填写其他订阅属性。
  5. 点击更新

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 如需修改推送端点网址,请运行 gcloud pubsub subscriptions modify-push-config 命令:

    gcloud pubsub subscriptions modify-push-config SUBSCRIPTION_ID \
        --push-endpoint=PUSH_ENDPOINT

    如果订阅已在使用拉取传送,则设置推送端点会将传送方法切换为推送传送。

    您可以通过将推送端点更改为空字符串,从推送传送切换为拉取传送。

REST

如需修改订阅的推送配置,请使用 projects.subscriptions.modifyPushConfig 方法:

请求:

必须使用 Authorization 标头中的访问令牌对请求进行身份验证。如需获取当前应用默认凭据的访问令牌,请运行以下命令:gcloud auth application-default print-access-token

POST https://pubsub.googleapis.com/v1/projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID:modifyPushConfig
Authorization: Bearer ACCESS_TOKEN
    

请求正文:

{
  "pushConfig": {
    "pushEndpoint": "PUSH_ENDPOINT"
  }
}

其中:

  • PROJECT_ID 是项目 ID。
  • SUBSCRIPTION_ID 是您的订阅 ID。
  • PUSH_ENDPOINT 是您要应用作为新推送端点的经过修改的网址。例如 https://myproject.appspot.com/myhandler
  • 响应:

    如果请求成功,响应将为空的 JSON 对象。

    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"
    )
    
    func updateEndpoint(w io.Writer, projectID, subID string, endpoint string) error {
    	// projectID := "my-project-id"
    	// subID := "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()
    
    	subConfig, err := client.Subscription(subID).Update(ctx, pubsub.SubscriptionConfigToUpdate{
    		PushConfig: &pubsub.PushConfig{Endpoint: endpoint},
    	})
    	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.pubsub.v1.PushConfig;
    import com.google.pubsub.v1.Subscription;
    import com.google.pubsub.v1.SubscriptionName;
    import java.io.IOException;
    
    public class UpdatePushConfigurationExample {
      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";
        String pushEndpoint = "https://my-test-project.appspot.com/push";
    
        updatePushConfigurationExample(projectId, subscriptionId, pushEndpoint);
      }
    
      public static void updatePushConfigurationExample(
          String projectId, String subscriptionId, String pushEndpoint) throws IOException {
        try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
          SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);
          PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(pushEndpoint).build();
          subscriptionAdminClient.modifyPushConfig(subscriptionName, pushConfig);
          Subscription subscription = subscriptionAdminClient.getSubscription(subscriptionName);
          System.out.println(
              "Updated push endpoint to: " + subscription.getPushConfig().getPushEndpoint());
        }
      }
    }

    Node.js

    /**
     * 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 modifyPushConfig(topicNameOrId, subscriptionNameOrId) {
      const options = {
        // Set to an HTTPS endpoint of your choice. If necessary, register
        // (authorize) the domain on which the server is hosted.
        pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`,
      };
    
      await pubSubClient
        .topic(topicNameOrId)
        .subscription(subscriptionNameOrId)
        .modifyPushConfig(options);
      console.log(`Modified push config for subscription ${subscriptionNameOrId}.`);
    }

    Node.js

    /**
     * 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, CreateSubscriptionOptions} from '@google-cloud/pubsub';
    
    // Creates a client; cache this for further use
    const pubSubClient = new PubSub();
    
    async function modifyPushConfig(
      topicNameOrId: string,
      subscriptionNameOrId: string
    ) {
      const options: CreateSubscriptionOptions = {
        // Set to an HTTPS endpoint of your choice. If necessary, register
        // (authorize) the domain on which the server is hosted.
        pushEndpoint: `https://${pubSubClient.projectId}.appspot.com/push`,
      };
    
      await pubSubClient
        .topic(topicNameOrId)
        .subscription(subscriptionNameOrId)
        .modifyPushConfig(options);
      console.log(`Modified push config for subscription ${subscriptionNameOrId}.`);
    }

    Python

    试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Python 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Python API 参考文档

    要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

    from google.cloud import pubsub_v1
    
    # TODO(developer)
    # project_id = "your-project-id"
    # topic_id = "your-topic-id"
    # subscription_id = "your-subscription-id"
    # endpoint = "https://my-test-project.appspot.com/push"
    
    subscriber = pubsub_v1.SubscriberClient()
    subscription_path = subscriber.subscription_path(project_id, subscription_id)
    
    push_config = pubsub_v1.types.PushConfig(push_endpoint=endpoint)
    
    subscription = pubsub_v1.types.Subscription(
        name=subscription_path, topic=topic_id, push_config=push_config
    )
    
    update_mask = {"paths": {"push_config"}}
    
    # Wrap the subscriber in a 'with' block to automatically call close() to
    # close the underlying gRPC channel when done.
    with subscriber:
        result = subscriber.update_subscription(
            request={"subscription": subscription, "update_mask": update_mask}
        )
    
    print(f"Subscription updated: {subscription_path}")
    print(f"New endpoint for subscription is: {result.push_config}.")

    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          = pubsub.subscription subscription_id
    subscription.endpoint = new_endpoint
    
    puts "Push endpoint updated."

    后续步骤