服务总线管理库Service Bus management libraries

Azure 服务总线管理库可以动态预配服务总线命名空间和实体。The Azure Service Bus management libraries can dynamically provision Service Bus namespaces and entities. 这样可以实现复杂的部署和消息方案,并能以编程方式确定要预配的实体。This enables complex deployments and messaging scenarios, and makes it possible to programmatically determine what entities to provision. 这些库目前可用于 .NET。These libraries are currently available for .NET.

受支持的功能Supported functionality

  • 创建、更新、删除命名空间Namespace creation, update, deletion
  • 创建、更新、删除队列Queue creation, update, deletion
  • 创建、更新、删除主题Topic creation, update, deletion
  • 创建、更新、删除订阅Subscription creation, update, deletion

先决条件Prerequisites

若要开始使用服务总线管理库,必须使用 Azure Active Directory (Azure AD) 服务进行身份验证。To get started using the Service Bus management libraries, you must authenticate with the Azure Active Directory (Azure AD) service. Azure AD 要求身份验证为服务主体,并且该主体提供对 Azure 资源的访问权限。Azure AD requires that you authenticate as a service principal, which provides access to your Azure resources. 有关创建服务主体的信息,请参阅以下文章之一:For information about creating a service principal, see one of these articles:

这些教程提供 AppId(客户端 ID)、TenantIdClientSecret(身份验证密钥),这些都将用于管理库进行的身份验证。These tutorials provide you with an AppId (Client ID), TenantId, and ClientSecret (authentication key), all of which are used for authentication by the management libraries. 对于用于运行的资源组,需要至少具有 Azure 服务总线数据所有者参与者权限 。You must have at-least Azure Service Bus Data Owner or Contributor permissions for the resource group on which you wish to run.

编程模式Programming pattern

所有服务总线资源的操纵模式都遵循常用协议:The pattern to manipulate any Service Bus resource follows a common protocol:

  1. 使用 Microsoft.IdentityModel.Clients.ActiveDirectory 库从 Azure AD 获取令牌:Obtain a token from Azure AD using the Microsoft.IdentityModel.Clients.ActiveDirectory library:

    var context = new AuthenticationContext($"https://login.chinacloudapi.cn/{tenantId}");
    
    var result = await context.AcquireTokenAsync("https://management.core.chinacloudapi.cn/", new ClientCredential(clientId, clientSecret));
    
  2. 创建 ServiceBusManagementClient 对象:Create the ServiceBusManagementClient object:

    var creds = new TokenCredentials(token);
    var sbClient = new ServiceBusManagementClient(creds)
    {
        SubscriptionId = SettingsCache["SubscriptionId"]
    };
    
  3. CreateOrUpdate 参数设置为指定值:Set the CreateOrUpdate parameters to your specified values:

    var queueParams = new QueueCreateOrUpdateParameters()
    {
        Location = SettingsCache["DataCenterLocation"],
        EnablePartitioning = true
    };
    
  4. 执行调用:Execute the call:

    await sbClient.Queues.CreateOrUpdateAsync(resourceGroupName, namespaceName, QueueName, queueParams);
    

完成创建队列的代码Complete code to create a queue

下面是创建服务总线队列的完整代码:Here is the complete code to create a Service Bus queue:

using System;
using System.Threading.Tasks;

using Microsoft.Azure.Management.ServiceBus;
using Microsoft.Azure.Management.ServiceBus.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;

namespace SBusADApp
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateQueue().GetAwaiter().GetResult();
        }

        private static async Task CreateQueue()
        {
            try
            {
                var subscriptionID = "<SUBSCRIPTION ID>";
                var resourceGroupName = "<RESOURCE GROUP NAME>";
                var namespaceName = "<SERVICE BUS NAMESPACE NAME>";
                var queueName = "<NAME OF QUEUE YOU WANT TO CREATE>";

                var token = await GetToken();

                var creds = new TokenCredentials(token);
                var sbClient = new ServiceBusManagementClient(creds)
                {
                    SubscriptionId = subscriptionID,
                };

                var queueParams = new SBQueue();

                Console.WriteLine("Creating queue...");
                await sbClient.Queues.CreateOrUpdateAsync(resourceGroupName, namespaceName, queueName, queueParams);
                Console.WriteLine("Created queue successfully.");
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not create a queue...");
                Console.WriteLine(e.Message);
                throw e;
            }
        }

        private static async Task<string> GetToken()
        {
            try
            {
                var tenantId = "<AZURE AD TENANT ID>";
                var clientId = "<APPLICATION/CLIENT ID>";
                var clientSecret = "<CLIENT SECRET>";

                var context = new AuthenticationContext($"https://login.chinacloudapi.cn/{tenantId}");

                var result = await context.AcquireTokenAsync(
                    "https://management.chinacloudapi.cn/",
                    new ClientCredential(clientId, clientSecret)
                );

                // If the token isn't a valid string, throw an error.
                if (string.IsNullOrEmpty(result.AccessToken))
                {
                    throw new Exception("Token result is empty!");
                }

                return result.AccessToken;
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not get a token...");
                Console.WriteLine(e.Message);
                throw e;
            }
        }

    }
}

Important

有关完整示例,请参阅 GitHub 上的 .NET 管理示例For a complete example, see the .NET management sample on GitHub.

后续步骤Next steps

Microsoft.Azure.Management.ServiceBus API 参考Microsoft.Azure.Management.ServiceBus API reference