在Android上使用带C#和GoogleCredentials的SubscriberClient.StartAsync

时间:2019-09-08 02:00:51

标签: c# android xamarin.forms google-cloud-pubsub

我一直在尝试在Android上使用带有C#和Xamarin的google cloud pub / sub。我已经能够使用使用GoogleCredentials创建的频道和JSON文件作为Android资产登录到系统。我可以创建一个SubscriptionServiceApiClient,连接到云,从我的项目中读取订阅并提取消息。这是该代码段:

AssetManager assets = this.Assets;

using (StreamReader sr = new StreamReader(assets.Open("creds.json")))
{
    content = sr.ReadToEnd();
}


GoogleCredential cred = GoogleCredential.FromJson(content);
cred.CreateScoped(SubscriberServiceApiClient.DefaultScopes);

Channel channel = new Channel(
    SubscriberServiceApiClient.DefaultEndpoint.Host,
    SubscriberServiceApiClient.DefaultEndpoint.Port, cred.ToChannelCredentials());

SubscriberServiceApiClient subscriberClient = SubscriberServiceApiClient.Create(channel);

SubscriptionName subscriptionName = new SubscriptionName("probject_blah", "blah_status");

PullResponse response = subscriberClient.Pull(subscriptionName, returnImmediately: true, maxMessages: 20);

// Print out each received message.
foreach (ReceivedMessage msg in response.ReceivedMessages)
{
    string text = Encoding.UTF8.GetString(msg.Message.Data.ToByteArray());
    Console.WriteLine($"Message {msg.Message.MessageId}: {text}");
    //subscriberClient.Acknowledge(subscriptionName, msg);
}

问题出在所有示例使用的SubscriberClient及其StartAsync方法上。看起来像这样:


// Pull messages from the subscription using SimpleSubscriber.
SubscriberClient subscriber = await SubscriberClient.CreateAsync(subscriptionName);
List<PubsubMessage> receivedMessages = new List<PubsubMessage>();
// Start the subscriber listening for messages.
await subscriber.StartAsync((msg, cancellationToken) =>
{
    receivedMessages.Add(msg);
    Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
    Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
    // Stop this subscriber after one message is received.
    // This is non-blocking, and the returned Task may be awaited.
    subscriber.StopAsync(TimeSpan.FromSeconds(15));
    // Return Reply.Ack to indicate this message has been handled.
    return Task.FromResult(SubscriberClient.Reply.Ack);
});

无法将Channel传递给类,并且出现连接错误。我想使用回调函数来处理消息,而不是定期提取消息。我已经能够在另一端的关联Python服务器上做到这一点。在该系统上,我可以将GOOGLE_APPLICATION_CREDENTIALS环境变量设置为json文件,这是首选的身份验证方式,但在Android上似乎不可能(或至少是直截了当)。

那我该如何让他工作呢?是否有设置GOOGLE_APPLICATION_CREDENTIALS变量的可靠方法?还是有另一种方法可以使这项工作奏效?在线上的代码示例是否过时?

0 个答案:

没有答案