《Windows Azure Platform 系列文章目录》
Azure Event Hub事件中心支持两种授权方式:
- Azure Active Directory
- Shared access signatures (SAS,共享访问签名)
针对第二种SAS的授权方式,Azure Portal上直接可以查看到具体的连接字符串,相对比较简单。
本文主要介绍第一种,使用Azure AD授权访问Event Hub。
在使用Azure AD授权之前,我们需要创建应用注册(App Registration),并获得tenant id, app id和app secret。
具体可以参考:Windows Azure AD (7) 创建配置应用程序和服务主体 (Application and Service Principal)
1.假设我们已经成功创建了一个应用注册(App Registration),如下图:
2.我们需要在RBAC上,设置这个应用注册的权限。
Azure 事件中心数据所有者,使用此角色可以授予对事件中心资源的完全访问权限。
Azure 事件中心数据发送者,使用此角色可以授予对事件中心资源的发送访问权限。
Azure 事件中心数据接收者,使用此角色可以授予对事件中心资源的使用/接收访问权限。
3.我们这里演示的内容,是通过AAD给Event Hub发送消息
4.我们打开Visual Studio,创建的项目类型为.Net Core。如下图:
5.设置项目名称为EventHubSender。步骤略。
6.在Program.cs中,增加引用
using System; using System.Text; using System.Threading.Tasks; using Azure.Core; using Azure.Messaging.EventHubs; using Azure.Messaging.EventHubs.Producer; using Azure.Identity;
7.在Nuget包管理中,增加以下package
8.在Class Program中,增加如下代码:
static EventHubProducerClient producerClient; //这里设置TenantID static readonly string TenantId = ""; //这里设置ClientID static readonly string ClientId = ""; //这里设置Client Secret static readonly string ClientSecret = ""; //这里设置Event Hub命名空间 static readonly string EventHubNamespace = "leieventhub01.servicebus.chinacloudapi.cn"; //这里设置Event Hub Name static readonly string EventHubName = "event01"; static async Task Main() { await ClientCredentialsScenarioAsync(); } static async Task ClientCredentialsScenarioAsync() {
var options = new ClientCertificateCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzureChina }; TokenCredential credential = new ClientSecretCredential(TenantId, ClientId, ClientSecret, options); // Create a producer client that you can use to send events to an event hub producerClient = new EventHubProducerClient(EventHubNamespace, EventHubName, credential); // Create a batch of events EventDataBatch eventBatch; for (int i = 1; i <= numOfEvents; i++) { eventBatch = await producerClient.CreateBatchAsync(); eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes($"Event {i}"))); await producerClient.SendAsync(eventBatch); Console.WriteLine($"A Message {i} has been sent"); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2017-09-24 Azure SQL Database (24) 使用新管理界面,创建跨数据中心标准地域复制(Standard Geo-Replication)