Google Cloud PubSub V1 使用 GCloud 模拟器

Google Cloud PubSub V1 using GCloud Emulator

我正在与 Google 使用 PubSub 模拟器通过 .NET 设置 Cloud PubSub 的文档进行斗争。

https://cloud.google.com/dotnet/docs/getting-started/using-pub-sub

https://cloud.google.com/pubsub/docs/publisher

https://cloud.google.com/pubsub/docs/emulator

来自 Rails 背景,我的任务是为 .NET 产品实施 Cloud PubSub,运行 我们在 .NET Core 上的 google 云,使其能够发布。

Google::Cloud::Pubsub.new(project: project_id, emulator_host: emulator_host)

根据使用 .NET 的文档,我不断回到以下内容:

PublisherServiceApiClient publisherClient = PublisherServiceApiClient.Create();
PublisherClient publisher = PublisherClient.Create(...)

但是,文档中使用的库 Google.Cloud.PubSub.V1 -Pre 不包含定义。

'PublisherClient' does not contain a definition for 'Create'

相反,我得到 CreateAsync,其中包含 TopicNamePublisherClient.ClientCreationSettingsPublisherClient.Settings

https://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.PubSub.V1/api/Google.Cloud.PubSub.V1.PublisherClient.html

我注意到 PublisherServiceApiClient 可以接受 Channel,但我对如何实现这一点感到困惑。

最后提出一个实际问题,目前如何在云中使用 .NET 实现 Cloud PubSub,然后在本地使用模拟器实现?除此之外,我是否使用了错误的库或错误的文档?

如有任何建议、指点或建议,我们将不胜感激。

我管理了一个令我满意的解决方案。

我没有使用 PublisherClient,而是单独使用 PublisherServiceApiClient

emulatorAddr = Environment.GetEnvironmentVariable("PUBSUB_EMULATOR_HOST");
if (emulatorAddr != null)
{
    channel = new Channel(emulatorAddr, ChannelCredentials.Insecure);
    pub = PublisherServiceApiClient.Create(channel);
}
else
{
    pub = PublisherServiceApiClient.Create();
}

这意味着发布比向 PublisherClient 发送字符串稍微复杂一些,但总体来说还不错。

PubsubMessage msg = new PubsubMessage
{
    Data = ByteString.CopyFromUtf8(JsonConvert.SerializeObject(payload))
};

pub.PublishAsync(topic, new[]{ msg });

如果项目 运行 在 Google Compute Engine 中,它将具有默认凭据。否则,无论您是 运行 本地模拟器还是 docker 中的模拟器,您都可以定义 PUBSUB_EMULATOR_HOST.

真正有用的是这个https://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.PubSub.V1/index.html

要使 PublisherClient 连接到本地模拟器,您需要将自定义 ServiceEndpointChannelCredentials 传递给 CreateAsync:

var serviceEndpoint = new ServiceEndpoint(theEmulatorHost, theEmulatorPort);

var publisherClient = await PublisherClient.CreateAsync(
    topicName,
    new PublisherClient.ClientCreationSettings(credentials: ChannelCredentials.Insecure, serviceEndpoint: serviceEndpoint));

要切换到真正的 PubSub,只需离开 ClientCreationSettings

您可以使用扩展方法 .WithEmulatorDetection(EmulatorDetection.EmulatorOrProduction)ClientCreationSettings 上使用 EmulatorDetection 属性。像这样:

PublisherClient publisher = await PublisherClient.CreateAsync(
        topicName, 
        new PublisherClient.ClientCreationSettings()
            .WithEmulatorDetection(EmulatorDetection.EmulatorOrProduction));

如果本地模拟器端点具有以下环境变量,这将起作用:PUBSUB_EMULATOR_HOST=localhost:8085

(如果你使用 Visual Studio 你可能需要重启 VS 才能检测到环境变量)

在 windows 中,我在使用 set PUBSUB_EMULATOR_HOST=localhost:8085 命令时遇到问题,所以我最终手动添加了它。

详情在这里:https://cloud.google.com/pubsub/docs/emulator

额外提示:您可以使用 curl 将主题直接添加到 API:curl -X PUT http://localhost:8085/v1/projects/my-project-name/topics/my-topic