事件中心管理库

可以使用 Azure 事件中心管理库动态设置事件中心命名空间和实体。 这种动态性可以实现复杂的部署和消息传送方案,以便能够以编程方式确定要预配的实体。 这些库目前可用于 .NET。

支持的功能

  • 命名空间创建、更新、删除
  • 事件中心创建、更新、删除
  • 使用者组创建、更新、删除

先决条件

要开始使用事件中心管理库,必须使用 Microsoft Entra ID 进行身份验证。 Microsoft Entra ID 要求以服务主体的身份进行身份验证,这可提供对 Azure 资源的访问权限。 有关创建服务主体的信息,请参阅以下文章之一:

这些教程提供 AppId(客户端 ID)、TenantIdClientSecret(身份验证密钥),这些都用于管理库进行的身份验证。 必须在资源组级别将 Microsoft Entra 应用程序添加到 Azure 事件中心数据所有者 角色。

示例代码

操作任何事件中心资源的模式都遵循通用协议:

  1. 使用 Microsoft.Identity.Client 库从 Microsoft Entra ID 获取令牌。
  2. 创建 EventHubManagementClient 对象。
  3. 然后,使用客户端对象创建事件中心命名空间和事件中心。

以下是创建事件中心命名空间和事件中心的示例代码。


namespace event_hub_dotnet_management
{
	using System;
	using System.Threading.Tasks;
	using Microsoft.Azure.ResourceManager.EventHubs;
	using Microsoft.Azure.ResourceManager.EventHubs.Models;
	using Microsoft.Identity.Client;
	using Microsoft.Rest;

	public static class EventHubManagementSample
	{
		private static string resourceGroupName = "<YOUR EXISTING RESOURCE GROUP NAME>";
		private static string namespaceName = "<EVENT HUBS NAMESPACE TO BE CREATED>";
		private const string eventHubName = "<EVENT HUB TO BE CREATED>";
		private const string location = "<REGION>"; //for example: "chinaeast"

		public static async Task Main()
		{
			// get a token from Microsoft Entra ID 
			var token = await GetToken();

			// create an EventHubManagementClient 
			var creds = new TokenCredentials(token);
			var ehClient = new EventHubManagementClient(creds)
			{
				SubscriptionId = "<AZURE SUBSCRIPTION ID>"
			};

			// create an Event Hubs namespace using the EventHubManagementClient
			await CreateNamespace(ehClient);

			// create an event hub using the EventHubManagementClient
			await CreateEventHub(ehClient);

			Console.WriteLine("Press a key to exit.");
			Console.ReadLine();
		}

		// Get an authentication token from Microsoft Entra ID first
		private static async Task<string> GetToken()
		{
			try
			{
				Console.WriteLine("Acquiring token...");

				var tenantId = "<AZURE TENANT ID>";

				// use the Microsoft Entra ID app that's a member of Azure Event Hubs Data Owner role at the resource group level
				var clientId = "<AZURE APPLICATION'S CLIENT ID>";
				var clientSecret = "<CLIENT SECRET>";

				IConfidentialClientApplication app;

				app = ConfidentialClientApplicationBuilder.Create(clientId)
							.WithClientSecret(clientSecret)
							.WithAuthority($"https://login.chinacloudapi.cn/{tenantId}")
							.Build();

				var result = await app.AcquireTokenForClient(new[] { $"https://management.core.chinacloudapi.cn/.default" })
					.ExecuteAsync()
					.ConfigureAwait(false);

				// 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 new token...");
				Console.WriteLine(e.Message);
				throw e;
			}
		}

		// Create an Event Hubs namespace
		private static async Task CreateNamespace(EventHubManagementClient ehClient)
		{
			try
			{
				Console.WriteLine("Creating namespace...");
				await ehClient.Namespaces.CreateOrUpdateAsync(resourceGroupName, namespaceName, new EHNamespace { Location = location });
				Console.WriteLine("Created namespace successfully.");
			}
			catch (Exception e)
			{
				Console.WriteLine("Could not create a namespace...");
				Console.WriteLine(e.Message);
			}
		}

		// Create an event hub
		private static async Task CreateEventHub(EventHubManagementClient ehClient)
		{
			try
			{
				Console.WriteLine("Creating Event Hub...");
				await ehClient.EventHubs.CreateOrUpdateAsync(resourceGroupName, namespaceName, eventHubName, new Eventhub());
				Console.WriteLine("Created Event Hub successfully.");
			}
			catch (Exception e)
			{
				Console.WriteLine("Could not create an Event Hub...");
				Console.WriteLine(e.Message);
			}
		}
	}
}

后续步骤