我正在与Google Docs争夺使用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 Cloud,使其能够发布。
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
,它接受了TopicName
,PublisherClient.ClientCreationSettings
和PublisherClient.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
连接到本地模拟器,您需要将自定义ServiceEndpoint
和ChannelCredentials
传递给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 才能检测到环境变量(
在窗口中,我在使用set PUBSUB_EMULATOR_HOST=localhost:8085
命令时遇到问题,所以我最终手动添加它。
详情请见:https://cloud.google.com/pubsub/docs/emulator
额外提示:您可以使用 curl: 将主题直接添加到 APIcurl -X PUT http://localhost:8085/v1/projects/my-project-name/topics/my-topic