azure-eventhub-java
microsoft/skills
使用 Azure Event Hubs Java SDK 建立即時串流應用程式,包括事件的傳送與接收、批次處理,以及適用於生產環境的事件處理器。
...展開全部Azure Event Hubs Java SDK
使用 Azure Event Hubs Java SDK 建立即時串流應用程式。
安裝
com.azure
azure-messaging-eventhubs
5.19.0
com.azure
azure-messaging-eventhubs-checkpointstore-blob
1.20.0
建立客戶端
EventHubProducerClient
import com.azure.messaging.eventhubs.EventHubProducerClient;
import com.azure.messaging.eventhubs.EventHubClientBuilder;
// 使用連線字串
EventHubProducerClient producer = new EventHubClientBuilder()
.connectionString("", "")
.buildProducerClient();
// 包含 EntityPath 的完整連線字串
EventHubProducerClient producer = new EventHubClientBuilder()
.connectionString("")
.buildProducerClient();
使用 DefaultAzureCredential
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
// 本地開發環境:DefaultAzureCredential。生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// 或者在生產環境中直接使用特定憑證:
// 請參閱 https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
EventHubProducerClient producer = new EventHubClientBuilder()
.fullyQualifiedNamespace(".servicebus.windows.net")
.eventHubName("")
.credential(credential)
.buildProducerClient();
EventHubConsumerClient
import com.azure.messaging.eventhubs.EventHubConsumerClient;
EventHubConsumerClient consumer = new EventHubClientBuilder()
.connectionString("", "")
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.buildConsumerClient();
非同步客戶端
import com.azure.messaging.eventhubs.EventHubProducerAsyncClient;
import com.azure.messaging.eventhubs.EventHubConsumerAsyncClient;
EventHubProducerAsyncClient asyncProducer = new EventHubClientBuilder()
.connectionString("", "")
.buildAsyncProducerClient();
EventHubConsumerAsyncClient asyncConsumer = new EventHubClientBuilder()
.connectionString("", "")
.consumerGroup("$Default")
.buildAsyncConsumerClient();
核心模式
傳送單一事件
import com.azure.messaging.eventhubs.EventData;
EventData eventData = new EventData("Hello, Event Hubs!");
producer.send(Collections.singletonList(eventData));
傳送事件批次
import com.azure.messaging.eventhubs.EventDataBatch;
import com.azure.messaging.eventhubs.models.CreateBatchOptions;
// 建立批次
EventDataBatch batch = producer.createBatch();
// 新增事件(若批次已滿則返回 false)
for (int i = 0; i < 100; i++) {
EventData event = new EventData("Event " + i);
if (!batch.tryAdd(event)) {
// 批次已滿,先傳送並建立新批次
producer.send(batch);
batch = producer.createBatch();
batch.tryAdd(event);
}
}
// 傳送剩餘的事件
if (batch.getCount() > 0) {
producer.send(batch);
}
傳送至特定分區
CreateBatchOptions options = new CreateBatchOptions()
.setPartitionId("0");
EventDataBatch batch = producer.createBatch(options);
batch.tryAdd(new EventData("分區 0 事件"));
producer.send(batch);
使用分區鍵發送
CreateBatchOptions options = new CreateBatchOptions()
.setPartitionKey("customer-123");
EventDataBatch batch = producer.createBatch(options);
batch.tryAdd(new EventData("客戶事件"));
producer.send(batch);
帶有屬性的事件
EventData event = new EventData("訂單已建立");
event.getProperties().put("orderId", "ORD-123");
event.getProperties().put("customerId", "CUST-456");
event.getProperties().put("priority", 1);
producer.send(Collections.singletonList(event));
接收事件(簡易版)
import com.azure.messaging.eventhubs.models.EventPosition;
import com.azure.messaging.eventhubs.models.PartitionEvent;
// 從特定分區接收
Iterable events = consumer.receiveFromPartition(
"0", // 區隔識別碼
10, // 最大事件數
EventPosition.earliest(), // 起始位置
Duration.ofSeconds(30) // 超時時間
);
for (PartitionEvent partitionEvent : events) {
EventData event = partitionEvent.getData();
System.out.println("正文: " + event.getBodyAsString());
System.out.println("序列號: " + event.getSequenceNumber());
System.out.println("偏移量: " + event.getOffset());
}
EventProcessorClient (生產環境)
import com.azure.messaging.eventhubs.EventProcessorClient;
import com.azure.messaging.eventhubs.EventProcessorClientBuilder;
import com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore;
import com.azure.storage.blob.BlobContainerAsyncClient;
import com.azure.storage.blob.BlobContainerClientBuilder;
// 建立檢查點儲存區
BlobContainerAsyncClient blobClient = new BlobContainerClientBuilder()
.connectionString("")
.containerName("checkpoints")
.buildAsyncClient();
// 建立處理器
EventProcessorClient processor = new EventProcessorClientBuilder()
.connectionString("", "")
.consumerGroup("$Default")
.checkpointStore(new BlobCheckpointStore(blobClient))
.processEvent(eventContext -> {
EventData event = eventContext.getEventData();
System.out.println("處理中: " + event.getBodyAsString());
// 處理完畢後建立檢查點
eventContext.updateCheckpoint();
})
.processError(errorContext -> {
System.err.println("錯誤: " + errorContext.getThrowable().getMessage());
System.err.println("區隔: " + errorContext.getPartitionContext().getPartitionId());
})
.buildEventProcessorClient();
// 開始處理
processor.start();
// 持續執行...
Thread.sleep(Duration.ofMinutes(5).toMillis());
// 正常停止
processor.stop();
批次處理
EventProcessorClient processor = new EventProcessorClientBuilder()
.connectionString("", "")
.consumerGroup("$Default")
.checkpointStore(new BlobCheckpointStore(blobClient))
.processEventBatch(eventBatchContext -> {
List events = eventBatchContext.getEvents();
System.out.printf("已接收 %d 個事件%n", events.size());
for (EventData event : events) {
// 處理每個事件
System.out.println(event.getBodyAsString());
}
// 批次處理後建立檢查點
eventBatchContext.updateCheckpoint();
}, 50) // maxBatchSize
.processError(errorContext -> {
System.err.println("錯誤:" + errorContext.getThrowable());
})
.buildEventProcessorClient();
非同步接收
asyncConsumer.receiveFromPartition("0", EventPosition.latest())
.subscribe(
partitionEvent -> {
EventData event = partitionEvent.getData();
System.out.println("已接收:" + event.getBodyAsString());
},
error -> System.err.println("錯誤:" + error),
() -> System.out.println("完成")
);
取得 Event Hub 屬性
// 取得 Event Hub 資訊
EventHubProperties hubProps = producer.getEventHubProperties();
System.out.println("Hub: " + hubProps.getName());
System.out.println("分區: " + hubProps.getPartitionIds());
// 取得分區資訊
PartitionProperties partitionProps = producer.getPartitionProperties("0");
System.out.println("起始序列號: " + partitionProps.getBeginningSequenceNumber());
System.out.println("起始序列號: " + partitionProps.getBeginningSequenceNumber());
System.out.println("最後序列號: " + partitionProps.getLastEnqueuedSequenceNumber());
System.out.println("最後偏移量: " + partitionProps.getLastEnqueuedOffset());
事件位置
// 從起始處開始
EventPosition.earliest()
// 從結尾處開始(僅限新事件)
EventPosition.latest()
// 從特定偏移量開始
EventPosition.fromOffset(12345L)
// 從特定序列號開始
EventPosition.fromSequenceNumber(100L)
// 從特定時間開始
EventPosition.fromEnqueuedTime(Instant.now().minus(Duration.ofHours(1)))
錯誤處理
import com.azure.messaging.eventhubs.models.ErrorContext;
.processError(errorContext -> {
Throwable error = errorContext.getThrowable();
String partitionId = errorContext.getPartitionContext().getPartitionId();
if (error instanceof AmqpException) {
AmqpException amqpError = (AmqpException) error;
if (amqpError.isTransient()) {
System.out.println("暫時性錯誤,將重新嘗試");
}
}
System.err.printf("分區 %s 發生錯誤:%s%n", partitionId, error.getMessage());
})
資源清理
// 務必關閉客戶端
try {
producer.send(batch);
} finally {
producer.close();
}
// 或使用 try-with-resources
try (EventHubProducerClient producer = new EventHubClientBuilder()
.connectionString(connectionString, eventHubName)
.buildProducerClient()) {
producer.send(events);
}
環境變數
EVENT_HUBS_CONNECTION_STRING=Endpoint=sb://.servicebus.windows.net/;SharedAccessKeyName=... # Entra ID 驗證的替代方案
EVENT_HUBS_NAME= # 事件中心名稱的必填項目
STORAGE_CONNECTION_STRING= # 用於檢查點功能的 Entra ID 驗證替代方案
AZURE_TOKEN_CREDENTIALS=prod # 僅在生產環境中使用 DefaultAzureCredential 時才需指定
最佳實務
- 使用 EventProcessorClient:在生產環境中,可提供負載平衡與檢查點功能
- 批次事件:使用
EventDataBatch可實現高效傳送 - 分區金鑰:用於在分區內確保事件排序順序
- 檢查點:處理後建立檢查點,以避免重複處理
- 錯誤處理:透過重試機制處理暫時性錯誤
- 關閉客戶端:完成後務必關閉生產者/消費者
觸發詞彙
- 「Event Hubs Java」
- 「Azure 事件串流」
- 「即時資料導入」
- 「EventProcessorClient」
- 「Event Hubs 發送端與接收端」
- 「分區處理」
---
name: azure-eventhub-java
description: Build real-time streaming applications with the Azure Event Hubs SDK for Java, including sending and receiving events, batch processing, and production-ready event processors.
license: MIT
---
# Azure Event Hubs SDK for Java
Build real-time streaming applications using the Azure Event Hubs SDK for Java.
## Installation
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventhubs</artifactId>
<version>5.19.0</version>
</dependency>
<!-- For checkpoint store (production) -->
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventhubs-checkpointstore-blob</artifactId>
<version>1.20.0</version>
</dependency>
```
## Client Creation
### EventHubProducerClient
```java
import com.azure.messaging.eventhubs.EventHubProducerClient;
import com.azure.messaging.eventhubs.EventHubClientBuilder;
// With connection string
EventHubProducerClient producer = new EventHubClientBuilder()
.connectionString("<connection-string>", "<event-hub-name>")
.buildProducerClient();
// Full connection string with EntityPath
EventHubProducerClient producer = new EventHubClientBuilder()
.connectionString("<connection-string-with-entity-path>")
.buildProducerClient();
```
### With DefaultAzureCredential
```java
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
EventHubProducerClient producer = new EventHubClientBuilder()
.fullyQualifiedNamespace("<namespace>.servicebus.windows.net")
.eventHubName("<event-hub-name>")
.credential(credential)
.buildProducerClient();
```
### EventHubConsumerClient
```java
import com.azure.messaging.eventhubs.EventHubConsumerClient;
EventHubConsumerClient consumer = new EventHubClientBuilder()
.connectionString("<connection-string>", "<event-hub-name>")
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.buildConsumerClient();
```
### Async Clients
```java
import com.azure.messaging.eventhubs.EventHubProducerAsyncClient;
import com.azure.messaging.eventhubs.EventHubConsumerAsyncClient;
EventHubProducerAsyncClient asyncProducer = new EventHubClientBuilder()
.connectionString("<connection-string>", "<event-hub-name>")
.buildAsyncProducerClient();
EventHubConsumerAsyncClient asyncConsumer = new EventHubClientBuilder()
.connectionString("<connection-string>", "<event-hub-name>")
.consumerGroup("$Default")
.buildAsyncConsumerClient();
```
## Core Patterns
### Send Single Event
```java
import com.azure.messaging.eventhubs.EventData;
EventData eventData = new EventData("Hello, Event Hubs!");
producer.send(Collections.singletonList(eventData));
```
### Send Event Batch
```java
import com.azure.messaging.eventhubs.EventDataBatch;
import com.azure.messaging.eventhubs.models.CreateBatchOptions;
// Create batch
EventDataBatch batch = producer.createBatch();
// Add events (returns false if batch is full)
for (int i = 0; i < 100; i++) {
EventData event = new EventData("Event " + i);
if (!batch.tryAdd(event)) {
// Batch is full, send and create new batch
producer.send(batch);
batch = producer.createBatch();
batch.tryAdd(event);
}
}
// Send remaining events
if (batch.getCount() > 0) {
producer.send(batch);
}
```
### Send to Specific Partition
```java
CreateBatchOptions options = new CreateBatchOptions()
.setPartitionId("0");
EventDataBatch batch = producer.createBatch(options);
batch.tryAdd(new EventData("Partition 0 event"));
producer.send(batch);
```
### Send with Partition Key
```java
CreateBatchOptions options = new CreateBatchOptions()
.setPartitionKey("customer-123");
EventDataBatch batch = producer.createBatch(options);
batch.tryAdd(new EventData("Customer event"));
producer.send(batch);
```
### Event with Properties
```java
EventData event = new EventData("Order created");
event.getProperties().put("orderId", "ORD-123");
event.getProperties().put("customerId", "CUST-456");
event.getProperties().put("priority", 1);
producer.send(Collections.singletonList(event));
```
### Receive Events (Simple)
```java
import com.azure.messaging.eventhubs.models.EventPosition;
import com.azure.messaging.eventhubs.models.PartitionEvent;
// Receive from specific partition
Iterable<PartitionEvent> events = consumer.receiveFromPartition(
"0", // partitionId
10, // maxEvents
EventPosition.earliest(), // startingPosition
Duration.ofSeconds(30) // timeout
);
for (PartitionEvent partitionEvent : events) {
EventData event = partitionEvent.getData();
System.out.println("Body: " + event.getBodyAsString());
System.out.println("Sequence: " + event.getSequenceNumber());
System.out.println("Offset: " + event.getOffset());
}
```
### EventProcessorClient (Production)
```java
import com.azure.messaging.eventhubs.EventProcessorClient;
import com.azure.messaging.eventhubs.EventProcessorClientBuilder;
import com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore;
import com.azure.storage.blob.BlobContainerAsyncClient;
import com.azure.storage.blob.BlobContainerClientBuilder;
// Create checkpoint store
BlobContainerAsyncClient blobClient = new BlobContainerClientBuilder()
.connectionString("<storage-connection-string>")
.containerName("checkpoints")
.buildAsyncClient();
// Create processor
EventProcessorClient processor = new EventProcessorClientBuilder()
.connectionString("<eventhub-connection-string>", "<event-hub-name>")
.consumerGroup("$Default")
.checkpointStore(new BlobCheckpointStore(blobClient))
.processEvent(eventContext -> {
EventData event = eventContext.getEventData();
System.out.println("Processing: " + event.getBodyAsString());
// Checkpoint after processing
eventContext.updateCheckpoint();
})
.processError(errorContext -> {
System.err.println("Error: " + errorContext.getThrowable().getMessage());
System.err.println("Partition: " + errorContext.getPartitionContext().getPartitionId());
})
.buildEventProcessorClient();
// Start processing
processor.start();
// Keep running...
Thread.sleep(Duration.ofMinutes(5).toMillis());
// Stop gracefully
processor.stop();
```
### Batch Processing
```java
EventProcessorClient processor = new EventProcessorClientBuilder()
.connectionString("<connection-string>", "<event-hub-name>")
.consumerGroup("$Default")
.checkpointStore(new BlobCheckpointStore(blobClient))
.processEventBatch(eventBatchContext -> {
List<EventData> events = eventBatchContext.getEvents();
System.out.printf("Received %d events%n", events.size());
for (EventData event : events) {
// Process each event
System.out.println(event.getBodyAsString());
}
// Checkpoint after batch
eventBatchContext.updateCheckpoint();
}, 50) // maxBatchSize
.processError(errorContext -> {
System.err.println("Error: " + errorContext.getThrowable());
})
.buildEventProcessorClient();
```
### Async Receiving
```java
asyncConsumer.receiveFromPartition("0", EventPosition.latest())
.subscribe(
partitionEvent -> {
EventData event = partitionEvent.getData();
System.out.println("Received: " + event.getBodyAsString());
},
error -> System.err.println("Error: " + error),
() -> System.out.println("Complete")
);
```
### Get Event Hub Properties
```java
// Get hub info
EventHubProperties hubProps = producer.getEventHubProperties();
System.out.println("Hub: " + hubProps.getName());
System.out.println("Partitions: " + hubProps.getPartitionIds());
// Get partition info
PartitionProperties partitionProps = producer.getPartitionProperties("0");
System.out.println("Begin sequence: " + partitionProps.getBeginningSequenceNumber());
System.out.println("Last sequence: " + partitionProps.getLastEnqueuedSequenceNumber());
System.out.println("Last offset: " + partitionProps.getLastEnqueuedOffset());
```
## Event Positions
```java
// Start from beginning
EventPosition.earliest()
// Start from end (new events only)
EventPosition.latest()
// From specific offset
EventPosition.fromOffset(12345L)
// From specific sequence number
EventPosition.fromSequenceNumber(100L)
// From specific time
EventPosition.fromEnqueuedTime(Instant.now().minus(Duration.ofHours(1)))
```
## Error Handling
```java
import com.azure.messaging.eventhubs.models.ErrorContext;
.processError(errorContext -> {
Throwable error = errorContext.getThrowable();
String partitionId = errorContext.getPartitionContext().getPartitionId();
if (error instanceof AmqpException) {
AmqpException amqpError = (AmqpException) error;
if (amqpError.isTransient()) {
System.out.println("Transient error, will retry");
}
}
System.err.printf("Error on partition %s: %s%n", partitionId, error.getMessage());
})
```
## Resource Cleanup
```java
// Always close clients
try {
producer.send(batch);
} finally {
producer.close();
}
// Or use try-with-resources
try (EventHubProducerClient producer = new EventHubClientBuilder()
.connectionString(connectionString, eventHubName)
.buildProducerClient()) {
producer.send(events);
}
```
## Environment Variables
```bash
EVENT_HUBS_CONNECTION_STRING=Endpoint=sb://<namespace>.servicebus.windows.net/;SharedAccessKeyName=... # Alternative to Entra ID auth
EVENT_HUBS_NAME=<event-hub-name> # Required for event hub name
STORAGE_CONNECTION_STRING=<for-checkpointing> # Alternative to Entra ID auth for checkpointing
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Best Practices
1. **Use EventProcessorClient**: For production, provides load balancing and checkpointing
2. **Batch Events**: Use `EventDataBatch` for efficient sending
3. **Partition Keys**: Use for ordering guarantees within a partition
4. **Checkpointing**: Checkpoint after processing to avoid reprocessing
5. **Error Handling**: Handle transient errors with retries
6. **Close Clients**: Always close producer/consumer when done
## Trigger Phrases
- "Event Hubs Java"
- "event streaming Azure"
- "real-time data ingestion"
- "EventProcessorClient"
- "event hub producer consumer"
- "partition processing"
所有檔案
0 個檔案安裝 azure-eventhub-java
請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。
下載 ZIP複製儲存庫並將技能檔案複製到您的專案中。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-java/skills/azure-eventhub-java # Copy SKILL.md to your .claude/skills/ directory
複製





首頁
