1. 创建一个.net framework的控制台程序
2. 在Nuget管理中添加Azure.Messaging.ServiceBus的package
Note: WindowsAzure.ServiceBus也能够提供我们今天联系所需要的功能,但Azure.Messaging.ServiceBus是最新的库,根据描述里写的WindowsAzure.ServiceBus会继续进行关键补丁的修复,但Azure.Messaging.ServiceBus确是更新的包。
如果你使用的是WindowsAzure.ServiceBus的包,可以参考这篇博客:
Dynamics CRM 365 and Azure Service Bus – Queue
3. 编写控制台程序
这里我使用的是微软文档里的官方代码,链接放到最后了
将Program.cs中的代码替换成下面的代码,并将connectionString替换成service bus命名空间的主连接字符串, 将queueName替换成你创建的队列的名称
如果不知道这两个变量的值去哪找,可以参考我之前写的博客:
using System;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
namespace QueueReceiver
{
class Program
{
// connection string to your Service Bus namespace
static string connectionString = "<NAMESPACE CONNECTION STRING>";
// name of your Service Bus queue
static string queueName = "<QUEUE NAME>";
// the client that owns the connection and can be used to create senders and receivers
static ServiceBusClient client;
// the processor that reads and processes messages from the queue
static ServiceBusProcessor processor;
// handle received messages
static async Task MessageHandler(ProcessMessageEventArgs args)
{
string body = args.Message.Body.ToString();
Console.WriteLine($"Received: {body}");
// complete the message. messages is deleted from the queue.
await args.CompleteMessageAsync(args.Message);
}
// handle any errors when receiving messages
static Task ErrorHandler(ProcessErrorEventArgs args)
{
Console.WriteLine(args.Exception.ToString());
return Task.CompletedTask;
}
static async Task Main()
{
// The Service Bus client types are safe to cache and use as a singleton for the lifetime
// of the application, which is best practice when messages are being published or read
// regularly.
//
// Create the client object that will be used to create sender and receiver objects
client = new ServiceBusClient(connectionString);
// create a processor that we can use to process the messages
processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions());
try
{
// add handler to process messages
processor.ProcessMessageAsync += MessageHandler;
// add handler to process any errors
processor.ProcessErrorAsync += ErrorHandler;
// start processing
await processor.StartProcessingAsync();
Console.WriteLine("Wait for a minute and then press any key to end the processing");
Console.ReadKey();
// stop processing
Console.WriteLine("\nStopping the receiver...");
await processor.StopProcessingAsync();
Console.WriteLine("Stopped receiving messages");
}
finally
{
// Calling DisposeAsync on client types is required to ensure that network
// resources and other unmanaged objects are properly cleaned up.
await processor.DisposeAsync();
await client.DisposeAsync();
}
}
}
}
4. 在运行程序前,如果你的service bus队列中有消息,你会在queue中发现下面message count不为0,并且current size也是有大小的
5. 运行程序,我们会看到我们接收到的消息
6. 再次回到service bus的队列中查看,我们会发现message count中的active和current size都已经为0了
如果没有清零,可以再次刷新下试试。
参考链接: