使用 C# 客户端库创建 SubscriberClient 时指定 Google 凭据

Specifying Google Credentials When Creating a SubscriberClient using C# Client Library

我已经为我们的服务设置了一个 GCP PubSub 处理器,它创建了一个 SubscriberClient 像这样

var subscriptionClient = await SubscriberClient.CreateAsync(subscriptionName);.

我设置了 GOOGLE_APPLICATION_CREDENTIALS 环境变量并指向有效的 SA 密钥。一切都按预期工作。

但是,我怎样才能在本地计算机上的 GOOGLE_APPLICATION_CREDENTIALS 环境变量上不 using/relying?

云存储客户端库允许您像这样创建存储客户端 StorageClient.Create(GoogleCredentials gcpCredentials); 我一直在使用 PubSub 客户端库寻找类似的东西,但没有找到任何东西。有 ChannelCredentials 但似乎不是用于此目的。

我确实看到 SubscriberServiceApiClientBuilder 允许您指定 JsonCredentials 但我没有在我的用例中使用该客户端。由于 SubscriberClientPublisherClient 更适合我的目的,因为文档中给出了以下内容:

PublisherClient and SubscriberClient provide simpler APIs for message publishing and subscribing. These classes offer considerably higher performance and simplicity, especially when working with higher message throughput.

谢谢

以与 PublisherClient 类似的方式手动创建 ChannelCredentials 并传入使用 GoogleCredentials.ToChannelCredentials() 设置的凭据初始化的 ClientCreationSettings 完成工作。

var subscriptionName = SubscriptionName.FromProjectSubscription("projectId", "subscriptionId");

// create GoogleCredentials
var gcpCredentials = <code that creates valid GoogleCredentials>;

// create ClientCreationSettings with credentials based on the GoogleCredentials created above
var settings = new SubscriberClient.ClientCreationSettings(credentials: gcpCredentials.ToChannelCredentials());

var client = await SubscriberClient.CreateAsync(<SubscriptionName>, settings);

我也在 GitHub googleapis/google-api-dotnet-client 回购中问过这个问题。如果您想了解更多信息:GitHub Issue 1764 Link