问题描述

当使用SDK连接到Azure Event Hub时,最常规的方式为使用连接字符串。这种做法参考官网文档就可成功完成代码:https://docs.azure.cn/zh-cn/event-hubs/event-hubs-java-get-started-send

只是,如果使用Azure AD认证方式进行访问,代码需要如何修改呢? 如何来使用AAD的 TokenCredential呢?

分析问题

在使用Connection String的时候,EventProcessorClientBuilder使用connectionString方法配置连接字符串。

如果使用Azure AD认证,则需要先根据AAD中注册应用获取到Client ID, Tenant ID, Client Secret,然后把这些内容设置为系统环境变量

  1. AZURE_TENANT_ID :对应AAD 注册应用页面的 Tenant ID
  2. AZURE_CLIENT_ID :对应AAD 注册应用页面的 Application (Client) ID
  3. AZURE_CLIENT_SECRET :对应AAD 注册应用的 Certificates & secrets 中创建的Client Secrets

然后使用 credential 初始化 EventProcessorClientBuilder 对象

注意点:

1) DefaultAzureCredentialBuilder 需要指定 Authority Host为 Azure China

2) EventProcessorClientBuilder . Credential 方法需要指定Event Hub Namespce 的域名

操作实现

第一步:为AAD注册应用赋予操作Event Hub Data的权限

Azure 提供了以下 Azure 内置角色,用于通过 Azure AD 和 OAuth 授予对事件中心数据的访问权限:

  1. Azure 事件中心数据所有者 (Azure Event Hubs Data Owner): 使用此角色可以授予对事件中心资源的完全访问权限。
  2. Azure 事件中心数据发送者 (Azure Event Hubs Data Sender) : 使用此角色可以授予对事件中心资源的发送访问权限。
  3. Azure 事件中心数据接收者 (Azure Event Hubs Data Receiver): 使用此角色可以授予对事件中心资源的使用/接收访问权限。

本实例中,只需要接收数据,所以只赋予了 Azure Event Hubs Data Receiver权限。

第二步:在Java 项目中添加SDK依赖

添加在pom.xml文件中 dependencies 部分的内容为:azure-identity , azure-messaging-eventhubs , azure-messaging-eventhubs-checkpointstore-blob,最好都是用最新版本,避免出现运行时出现类型冲突或找不到

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5.  
  6. <groupId>com.example</groupId>
  7. <artifactId>spdemo</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9.  
  10. <name>spdemo</name>
  11. <!-- FIXME change it to the project's website -->
  12. <url>http://www.example.com</url>
  13.  
  14. <properties>
  15. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  16. <maven.compiler.source>1.8</maven.compiler.source>
  17. <maven.compiler.target>1.8</maven.compiler.target>
  18. </properties>
  19.  
  20. <dependencies>
  21. <dependency>
  22. <groupId>com.azure</groupId>
  23. <artifactId>azure-messaging-eventhubs</artifactId>
  24. <version>5.12.2</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>com.azure</groupId>
  28. <artifactId>azure-messaging-eventhubs-checkpointstore-blob</artifactId>
  29. <version>1.14.0</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>com.azure</groupId>
  33. <artifactId>azure-identity</artifactId>
  34. <version>1.5.3</version>
  35. </dependency>
  36. <dependency>
  37. <groupId>junit</groupId>
  38. <artifactId>junit</artifactId>
  39. <version>4.11</version>
  40. <scope>test</scope>
  41. </dependency>
  42. </dependencies>
  43.  
  44. <build>
  45. <plugins>
  46. <plugin>
  47. <groupId>org.apache.maven.plugins</groupId>
  48. <artifactId>maven-assembly-plugin</artifactId>
  49. <version>2.5.5</version>
  50. <configuration>
  51. <archive>
  52. <manifest>
  53. <mainClass>com.example.App</mainClass>
  54. </manifest>
  55. </archive>
  56. <descriptorRefs>
  57. <descriptorRef>jar-with-dependencies</descriptorRef>
  58. </descriptorRefs>
  59. </configuration>
  60. </plugin>
  61. </plugins>
  62. </build>
  63. </project>

第三步:添加完整代码

  1. package com.example;
  2.  
  3. import com.azure.core.credential.TokenCredential;
  4. import com.azure.identity.AzureAuthorityHosts;
  5. import com.azure.identity.DefaultAzureCredentialBuilder;
  6. import com.azure.messaging.eventhubs.*;
  7. import com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore;
  8. import com.azure.messaging.eventhubs.models.*;
  9. import com.azure.storage.blob.*;
  10.  
  11. import java.io.IOException;
  12. import java.sql.Date;
  13. import java.time.Instant;
  14. import java.time.temporal.TemporalUnit;
  15. import java.util.HashMap;
  16. import java.util.Map;
  17. import java.util.function.Consumer;
  18.  
  19. /**
  20. * Hello world!
  21. *
  22. */
  23. public class App {
  24. // private static final String connectionString ="<connectionString>";
  25. // private static final String eventHubName = "<eventHubName>";
  26. // private static final String storageConnectionString = "<storageConnectionString>";
  27. // private static final String storageContainerName = "<storageContainerName>";
  28.  
  29. public static void main(String[] args) throws IOException {
  30. System.out.println("Hello World!");
  31.  
  32. // String connectionString ="<connectionString>";
  33. // The fully qualified namespace for the Event Hubs instance. This is likely to
  34. // be similar to:
  35. // {your-namespace}.servicebus.windows.net
  36. // String fullyQualifiedNamespace ="<your event hub namespace>.servicebus.chinacloudapi.cn";
  37. // String eventHubName = "<eventHubName>";
  38.  
  39. String storageConnectionString = System.getenv("storageConnectionString");
  40. String storageContainerName = System.getenv("storageContainerName");
  41. String fullyQualifiedNamespace = System.getenv("fullyQualifiedNamespace");
  42. String eventHubName = System.getenv("eventHubName");
  43.  
  44. TokenCredential credential = new DefaultAzureCredentialBuilder().authorityHost(AzureAuthorityHosts.AZURE_CHINA)
  45. .build();
  46.  
  47. // Create a blob container client that you use later to build an event processor
  48. // client to receive and process events
  49. BlobContainerAsyncClient blobContainerAsyncClient = new BlobContainerClientBuilder()
  50. .connectionString(storageConnectionString)
  51. .containerName(storageContainerName)
  52. .buildAsyncClient();
  53.  
  54. // EventHubProducerClient
  55. // EventHubProducerClient client = new EventHubClientBuilder()
  56. // .credential(fullyQualifiedNamespace, eventHubName, credential)
  57. // .buildProducerClient();
  58.  
  59. Map<String, EventPosition> initialPartitionEventPosition = new HashMap<>();
  60. initialPartitionEventPosition.put("0", EventPosition.fromSequenceNumber(3000));
  61.  
  62. // EventProcessorClientBuilder
  63. // Create a builder object that you will use later to build an event processor
  64. // client to receive and process events and errors.
  65. EventProcessorClientBuilder eventProcessorClientBuilder = new EventProcessorClientBuilder()
  66. // .connectionString(connectionString, eventHubName)
  67. .credential(fullyQualifiedNamespace, eventHubName, credential)
  68. .initialPartitionEventPosition(initialPartitionEventPosition)
  69. .consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
  70. .processEvent(PARTITION_PROCESSOR)
  71. .processError(ERROR_HANDLER)
  72. .checkpointStore(new BlobCheckpointStore(blobContainerAsyncClient));
  73.  
  74. // EventPosition.f
  75. // Use the builder object to create an event processor client
  76. EventProcessorClient eventProcessorClient = eventProcessorClientBuilder.buildEventProcessorClient();
  77.  
  78. System.out.println("Starting event processor");
  79. eventProcessorClient.start();
  80.  
  81. System.out.println("Press enter to stop.");
  82. System.in.read();
  83.  
  84. System.out.println("Stopping event processor");
  85. eventProcessorClient.stop();
  86. System.out.println("Event processor stopped.");
  87.  
  88. System.out.println("Exiting process");
  89.  
  90. }
  91.  
  92. public static final Consumer<EventContext> PARTITION_PROCESSOR = eventContext -> {
  93. PartitionContext partitionContext = eventContext.getPartitionContext();
  94. EventData eventData = eventContext.getEventData();
  95.  
  96. System.out.printf("Processing event from partition %s with sequence number %d with body: %s%n",
  97. partitionContext.getPartitionId(), eventData.getSequenceNumber(), eventData.getBodyAsString());
  98.  
  99. // Every 10 events received, it will update the checkpoint stored in Azure Blob
  100. // Storage.
  101. if (eventData.getSequenceNumber() % 10 == 0) {
  102. eventContext.updateCheckpoint();
  103. }
  104. };
  105.  
  106. public static final Consumer<ErrorContext> ERROR_HANDLER = errorContext -> {
  107. System.out.printf("Error occurred in partition processor for partition %s, %s.%n",
  108. errorContext.getPartitionContext().getPartitionId(),
  109. errorContext.getThrowable());
  110. };
  111. }

附录:自定义设置 Event Position,当程序运行时,指定从Event Hub中获取消息的 Sequence Number

使用EventPosition对象中的fromSequenceNumber方法,可以指定一个序列号,Consume端会根据这个号码获取之后的消息。其他的方法还有 fromOffset(指定游标) / fromEnqueuedTime(指定一个时间点,获取之后的消息) / earliest(从最早开始) / latest(从最后开始获取新的数据,旧数据不获取)

  1. Map<String, EventPosition> initialPartitionEventPosition = new HashMap<>();
  2. initialPartitionEventPosition.put("0", EventPosition.fromSequenceNumber(3000));

注意:

Map<String, EventPosition> 中的String 对象为Event Hub的分区ID,如果Event Hub有2个分区,则它的值分别时0,1.

EventPosition 设置的值,只在Storage Account所保存在CheckPoint Store中的值没有,或者小于此处设定的值时,才会起效果。否则,Consume 会根据从Checkpoint中获取的SequenceNumber为准。

参考资料

授予对 Azure 事件中心的访问权限 :https://docs.azure.cn/zh-cn/event-hubs/authorize-access-event-hubs

对使用 Azure Active Directory 访问事件中心资源的应用程序进行身份验证 : https://docs.azure.cn/zh-cn/event-hubs/authenticate-application

使用 Java 向/从 Azure 事件中心 (azure-messaging-eventhubs) 发送/接收事件 : https://docs.azure.cn/zh-cn/event-hubs/event-hubs-java-get-started-send

 [END]

 

 

【Azure 事件中心】使用Azure AD认证方式创建Event Hub Consume Client + 自定义Event Position的更多相关文章

  1. 【Azure 事件中心】Azure Event Hub 新功能尝试 -- 异地灾难恢复 (Geo-Disaster Recovery)

    问题描述 关于Event Hub(事件中心)的灾备方案,大多数就是新建另外一个备用的Event Hub,当主Event Hub出现不可用的情况时,就需要切换到备Event Hub上. 而在切换的过程中 ...

  2. 【Azure 事件中心】在微软云中国区 (Mooncake) 上实验以Apache Kafka协议方式发送/接受Event Hubs消息 (Java版)

    问题描述 事件中心提供 Kafka 终结点,现有的基于 Kafka 的应用程序可将该终结点用作运行你自己的 Kafka 群集的替代方案. 事件中心可与许多现有 Kafka 应用程序配合使用.在Azur ...

  3. 【Azure 事件中心】EPH (EventProcessorHost) 消费端观察到多次Shutdown,LeaseLost的error信息,这是什么情况呢?

    问题详情 使用EPH获取Event Hub数据时,多次出现连接shutdown和LeaseLost的error  ,截取某一次的error log如: Time:2021-03-10 08:43:48 ...

  4. 【Azure 事件中心】为应用程序网关(Application Gateway with WAF) 配置诊断日志,发送到事件中心

    问题描述 在Application Gateway中,开启WAF(Web application firewall)后,现在需要把访问的日志输出到第三方分析代码中进行分析,如何来获取WAF的诊断日志呢 ...

  5. 【Azure 事件中心】Event Hub 无法连接,出现 Did not observe any item or terminal signal within 60000ms in 'flatMapMany' 的错误消息

    问题描述 使用Java SDK连接Azure Event Hub,一直出现 java.util.concurrent.TimeoutException 异常, 消息为:java.util.concur ...

  6. 【Azure 事件中心】 org.slf4j.Logger 收集 Event Hub SDK(Java) 输出日志并以文件形式保存

    问题描述 在使用Azure Event Hub的SDK时候,常规情况下,发现示例代码中并没有SDK内部的日志输出.因为在Java项目中,没有添加 SLF4J 依赖,已致于在启动时候有如下提示: SLF ...

  7. 微软公有云事件中心(Azure Event Hubs)在开放物联网大会(OIOT)啼声初试

     发布于 2014-12-29 作者 刘 天栋 2014年12月18日,InfoQ在京召开开放物联网大会(Open IOT Conference),微软开放技术(中国)资深项目经理陈岭在大会中针对 ...

  8. 【Azure 事件中心】azure-spring-cloud-stream-binder-eventhubs客户端组件问题, 实践消息非顺序可达

    问题描述 查阅了Azure的官方文档( 将事件发送到特定分区: https://docs.azure.cn/zh-cn/event-hubs/event-hubs-availability-and-c ...

  9. 【Azure 事件中心】在Service Bus Explorer工具种查看到EventHub数据在分区中的各种属性问题

    问题描述 通过Service Bus Explorer工具,查看到Event Hub的属性值,从而产生的问题及讨论: Size in Bytes:   这个是表示当前分区可以存储的最大字节数吗? La ...

随机推荐

  1. 【Java分享客栈】未来迈向高级工程师绕不过的技能:JMeter压测

    前言 因为工作需要,久违的从自己的有道云笔记中去寻找压测相关的内容,翻开之后发现还不错,温故一遍后顺便整理出来分享给大家. 题外话,工作8年多,有道云笔记不知不觉都6G多了,扫一眼下来尽是云烟过往,竟 ...

  2. 封装axios请求

    import axios from 'axios' import router from '@/router' axios.defaults.baseURL = system.requestBaseU ...

  3. vsftp 详解

    1.默认配置: 1>允许匿名用户和本地用户登陆.     anonymous_enable=YES     local_enable=YES2>匿名用户使用的登陆名为ftp或anonymo ...

  4. LVS+keepalived高可用

    1.keeplived相关 1.1工作原理 Keepalived 是一个基于VRRP协议来实现的LVS服务高可用方案,可以解决静态路由出现的单点故障问题. 在一个LVS服务集群中通常有主服务器(MAS ...

  5. linux基本命令续(杂糅和转)

    此处使用CP 命令复制/etc/profile和/etc/init.d/network到家目录下,当然也可以指定其他目录如./ 根目录等. 在2提示处,如果输错了文字,可以ctrl+backspace ...

  6. Dcoker镜像管理与容器应用

    Dcoker镜像管理与容器应用 docker基于镜像创建容器 相同版本的镜像只允许存在一个 同一个镜像可以创建多个容器 镜像管理 [root@localhost ~]# docker pull cen ...

  7. Django——表单

    一.前言 看了下教程,以为表单很简单呢,结果搞了一两个钟才弄懂,哈哈哈,所以说不要小瞧每一件事. 先说明下HTTP请求: HTTP协议以"请求-回复"的方式工作.客户发送请求时,可 ...

  8. JS:条件语句3

    1.while while 语句只要指定条件为 true,就会执行循环. 语法: while(条件){ 语句: } 例: var i = 0; while (i < 5) { console.l ...

  9. Redis 切片集群的数据倾斜分析

    Redis 中如何应对数据倾斜 什么是数据倾斜 数据量倾斜 bigkey导致倾斜 Slot分配不均衡导致倾斜 Hash Tag导致倾斜 数据访问倾斜 如何发现 Hot Key Hot Key 如何解决 ...

  10. ansible在linux和windows批量部署zabbix-agent2

    --- - hosts: linux tasks: - name: copy centos 7 zabbix-agent2 copy: src=zabbix-agent2-5.0.11-1.el7.x ...