Azure Lei Zhang的博客

weibo: LeiZhang的微博/QQ: 185165016/QQ群:319036205/邮箱:leizhang1984@outlook.com/TeL:139-161-22926

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

  《Windows Azure Platform 系列文章目录

 

  Azure Event Hub事件中心支持两种授权方式:

  1. Azure Active Directory
  2. 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"); } }

 

   

posted on 2021-09-24 11:52  Lei Zhang的博客  阅读(271)  评论(0编辑  收藏  举报