《Windows Azure Platform 系列文章目录》
本文介绍的是,国内由世纪互联运维的Azure China
在笔者之前的文档中,我们链接Service Bus,都是通过链接字符串Connection String来连接的。
Windows Azure Service Bus (2) 队列(Queue)入门
Azure Service Principal,类似AWS Application。是通过API或者SDK的方式,开发使用。
我们可以通过Service Principal,来连接Azure Service Bus。
1.首先我们先创建1个Service Principal,具体步骤:Azure AD (8) 创建配置应用程序和服务主体 (Application and Service Principal)
2.在RBAC里,把Service Principal设置权限为Azure Service Bus Data Owner
上面三个Role的区别:
(1)Azure Service Bus Data Owner,具有全部权限(可以新增、或者删除Sevice Bus对象),对Service Bus数据可以读,也可以写
(2)Azure Service Bus Data Receiver,对Service Bus操作只读(不能删除Service Bus对象),对Service Bus数据只读
(3)Azure Service Bus Data Sender,对Service Bus操作只读(不能删除Service Bus对象),对Service Bus数据可以发送
3.新建Visual Studio Console项目,使用下面的代码:
using Azure.Messaging.ServiceBus; using Azure.Identity; using Azure.Core; using Microsoft.Identity.Client; // name of your Service Bus queue // the client that owns the connection and can be used to create senders and receivers ServiceBusClient client; // the sender used to publish messages to the queue ServiceBusSender sender; // number of messages to be sent to the queue const int numOfMessages = 3; // 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. // // Set the transport type to AmqpWebSockets so that the ServiceBusClient uses the port 443. // If you use the default AmqpTcp, ensure that ports 5671 and 5672 are open. var clientOptions = new ServiceBusClientOptions { TransportType = ServiceBusTransportType.AmqpWebSockets }; string tenantid = ""; string clientid = ""; string clientsecret = ""; ClientSecretCredentialOptions opts = new ClientSecretCredentialOptions() { AuthorityHost = AzureAuthorityHosts.AzureChina }; TokenCredential credential = new ClientSecretCredential(tenantid, clientid, clientsecret, opts); //这里输入Sevice Bus的访问url,这里是我的演示环境 client = new ServiceBusClient("leiservicebus01.servicebus.chinacloudapi.cn", credential); //这里我用的队列名称为queue01 sender = client.CreateSender("queue01"); // create a batch using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync(); for (int i = 1; i <= numOfMessages; i++) { // try adding a message to the batch if (!messageBatch.TryAddMessage(new ServiceBusMessage($"Message {i}"))) { // if it is too large for the batch throw new Exception($"The message {i} is too large to fit in the batch."); } } try { // Use the producer client to send the batch of messages to the Service Bus queue await sender.SendMessagesAsync(messageBatch); Console.WriteLine($"A batch of {numOfMessages} messages has been published to the queue."); } finally { // Calling DisposeAsync on client types is required to ensure that network // resources and other unmanaged objects are properly cleaned up. await sender.DisposeAsync(); await client.DisposeAsync(); } Console.WriteLine("Press any key to end the application"); Console.ReadKey();