编写和响应 Pub/Sub 消息

区域 ID

REGION_ID 是 Google 根据您在创建应用时选择的区域分配的缩写代码。此代码不对应于国家/地区或省,尽管某些区域 ID 可能类似于常用国家/地区代码和省代码。对于 2020 年 2 月以后创建的应用,REGION_ID.r 包含在 App Engine 网址中。对于在此日期之前创建的现有应用,网址中的区域 ID 是可选的。

详细了解区域 ID

Pub/Sub 可在应用之间提供可靠的多对多异步消息传递服务。发布者应用可以向某一主题发送消息,其他应用可以订阅该主题以接收消息。

本文档介绍如何使用 Cloud 客户端库在.NET 应用中发送和接收 Pub/Sub 消息。

前提条件

克隆示例应用

将示例应用复制到本地机器,然后导航到 pubsub 目录:

git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples
cd dotnet-docs-samples/appengine/flexible/pubsub

创建主题和订阅

创建主题和订阅,其中包括指定 Pub/Sub 服务器应该向其发送请求的端点:

gcloud pubsub topics create YOUR_TOPIC
gcloud pubsub subscriptions create YOUR_SUBSCRIPTION `
    --topic YOUR_TOPIC `
    --push-endpoint `
    https://YOUR_PROJECT_ID.REGION_ID.r.appspot.com/pubsub/push?token=YOUR_SECRET_TOKEN `
    --ack-deadline 10

设置环境变量

修改 appsettings.json 文件以设置您的项目 ID:

{
  "Pubsub": {
    "ProjectId": "your-project-id",
    "VerificationToken": "your-secret-token",
    "TopicId": "your-topic",
    "SubscriptionId": "your-subscription",
    "AuthSubscriptionId": "your-auth-subscription",
    "ServiceAccountEmail": "your-service-account-email"
  },

  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

代码审核

示例应用使用 Cloud 客户端库

[HttpGet]
[HttpPost]
public IActionResult Index(MessageForm messageForm)
{
    var model = new MessageList();
    if (!_options.HasGoodProjectId())
    {
        model.MissingProjectId = true;
        return View(model);
    }
    if (!string.IsNullOrEmpty(messageForm.Message))
    {
        // Publish the message.
        var pubsubMessage = new PubsubMessage()
        {
            Data = ByteString.CopyFromUtf8(messageForm.Message)
        };
        pubsubMessage.Attributes["token"] = _options.VerificationToken;
        _publisher.PublishAsync(pubsubMessage);
        model.PublishedMessage = messageForm.Message;
    }
    // Render the current list of messages.
    model.Messages = s_receivedMessages.ToArray();
    model.AuthMessages = s_authenticatedMessages.ToArray();
    return View(model);
}

在本地运行示例

在本地运行时,您可以借助 Google Cloud CLI 提供身份验证以使用 Google Cloud API。假设您按照前提条件中的说明设置了环境,那么您已经运行了 gcloud init 命令,该命令可提供此身份验证。

要在本地运行示例应用,请执行以下操作:

Visual Studio

  1. 使用 Visual Studio 打开 dotnet-docs-samples\appengine\flexible\AppEngineFlex.sln

  2. 在解决方案资源管理器中,右键点击 Pubsub,然后选择调试 > 启动新实例

命令行

  1. dotnet-docs-samples\appengine\flexible\Pubsub 目录运行以下命令:

    dotnet restore
    dotnet run
    
  2. 在网络浏览器中输入以下地址:

    http://localhost:5000/
    

模拟推送通知

应用可以在本地发送消息,但无法在本地接收推送消息。但是,您可以向本地推送通知端点发送 HTTP 请求来模拟推送消息。该示例包含文件 sample_message.json

如需发送 HTTP POST 请求,请使用以下代码:

Get-Content -Raw .\sample_message.json | Invoke-WebRequest -Uri
http://localhost:5000/Push?token=your-secret-token -Method POST -ContentType
'text/json' -OutFile out.txt

请求完成后,您可以刷新 localhost:5000 并在收到的消息列表中查看该消息。

在 App Engine 上运行应用

如需使用 gcloud 命令行工具将演示应用部署到 App Engine,请从 app.yaml 文件所在的目录运行以下命令:

Visual Studio

要部署 Hello World 应用,请执行以下操作:

  1. 使用 Visual Studio 打开 dotnet-docs-samples\appengine\flexible\AppEngineFlex.sln
  2. 在解决方案资源管理器中,右键点击 Pubsub,然后选择 Publish to Google Cloud...(发布到 Google Cloud…)
  3. 点击 App Engine Flex(App Engine 柔性环境)。
  4. 点击 Publish(发布)。

命令行

dotnet-docs-samples\appengine\flexible\Pubsub 目录运行以下命令:
dotnet restore
dotnet publish
cd bin\Debug\netcoreapp2.1\publish
gcloud app deploy

您现在可以通过 https://PROJECT_ID.REGION_ID.r.appspot.com 访问该应用。您可以使用表单提交消息,但无法保证您的哪个应用实例会收到通知。您可以发送多条消息并刷新页面,以查看收到的消息。