如何从天蓝色服务总线上读取消息

时间:2019-12-04 16:42:54

标签: c# azure-functions azureservicebus

我正在尝试使用C#天蓝色函数从队列中读取消息(通知而不是轮询)。

我目前正在使用控制台应用程序将消息推送到队列中,请参见下文。

似乎有两种不同的产品,一个是azure服务总线,另一个是存储帐户中的队列。以下代码使用后面的代码,我不确定如何读取队列的消息吗?

非常感谢,

代码示例

StorageCredentials creds = new StorageCredentials(accountname, accountkey);
        CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
        CloudQueueClient queueClient = account.CreateCloudQueueClient();
        CloudQueue queue = queueClient.GetQueueReference("test-queue");
        queue.CreateIfNotExists();
        while (true)
        {
            CloudQueueMessage message = new CloudQueueMessage(JsonConvert.SerializeObject("my message"));
            queue.AddMessage(message);
        }

更新

在评论和以下专家建议的链接之后,我尝试了以下代码示例将消息推送到Azure Service Bus(即存储帐户中没有队列)

namespace ConsoleApp1
{
    using System;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Azure.ServiceBus;

    class Program
    {
        const string ServiceBusConnectionString = "Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=xxx;SharedAccessKey=xxx";
        const string QueueName = "name_of_queue";
        static IQueueClient queueClient;

        public static async Task Main(string[] args)
        {
            const int numberOfMessages = 10;
            queueClient = new QueueClient(ServiceBusConnectionString, QueueName);

            await SendMessagesAsync(numberOfMessages);

            await queueClient.CloseAsync();
        }

        static async Task SendMessagesAsync(int numberOfMessagesToSend)
        {
            for (var i = 0; i < numberOfMessagesToSend; i++)
            {
                string messageBody = $"Message {i}";
                var message = new Message(Encoding.UTF8.GetBytes(messageBody));

                Console.WriteLine($"Sending message: {messageBody}");

                // Send the message to the queue
                try
                {
                    await queueClient.SendAsync(message);  // this line
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}

当我在控制台窗口上方运行代码时,什么也不做,没有错误消息,只是什么都没有。奇怪。在Azure服务总线概述中,活动消息计数为零。

我正在使用此示例项目,但是queueClient.SendAsync永远不会返回。我是否需要在权限中设置一些天蓝色的内容?

https://github.com/Azure/azure-service-bus

最终收到错误

  

连接尝试失败,因为被连接方未   一段时间后正确响应或建立连接   由于连接的主机未能响应而失败

我可以在门户网站服务总线屏幕上看到请求

1 个答案:

答案 0 :(得分:1)

这些是您想要的吗?

1。如果要从azure服务总线队列中获取消息:

using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;

namespace ConsoleApp2
{
    class Program
    {
        const string ServiceBusConnectionString = "xxxxxx";
        const string QueueName = "xxx";
        static IQueueClient queueClient;
        public static async Task Main(string[] args)
        {
            queueClient = new QueueClient(ServiceBusConnectionString, QueueName);

            RegisterOnMessageHandlerAndReceiveMessages();

            Console.ReadKey();

            await queueClient.CloseAsync();
        }
        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 10,
                AutoComplete = false
            };
            queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
        }
        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
            await queueClient.CompleteAsync(message.SystemProperties.LockToken);
        }
        static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
            var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
            Console.WriteLine("Exception context for troubleshooting:");
            Console.WriteLine($"- Endpoint: {context.Endpoint}");
            Console.WriteLine($"- Entity Path: {context.EntityPath}");
            Console.WriteLine($"- Executing Action: {context.Action}");
            return Task.CompletedTask;
        }
    }
}

在从服务总线队列接收消息之前,我已将消息放入队列。 结果是:

enter image description here

2。如果要从Azure存储队列中获取消息:

using System;
using Microsoft.Azure; 
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Queue;

namespace ReceiveMessageFromAzureStorageQueue
{
    class Program
    {
        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("xxxxxx");
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            CloudQueue queue = queueClient.GetQueueReference("xxx");
            CloudQueueMessage peekedMessage = queue.PeekMessage();
            queue.FetchAttributes();
            int? cachedMessageCount = queue.ApproximateMessageCount;
            Console.WriteLine("Number of messages in queue: " + cachedMessageCount);
            for(int i=0; i<cachedMessageCount; i++) {
                    System.Threading.Thread.Sleep(10);
                    CloudQueueMessage retrievedMessage = queue.GetMessage(TimeSpan.FromMilliseconds(10));
                    Console.WriteLine(retrievedMessage.AsString);
                    queue.DeleteMessage(retrievedMessage);
            }
            Console.WriteLine("Already Read.");
        }
    }
}

在接收到消息之前,仍将消息放入azure存储队列中。 结果是:

enter image description here

如果您还有其他疑问,请告诉我。