azure-eventhub-java
microsoft/skills
Создавайте приложения для потоковой передачи данных в режиме реального времени с помощью SDK Azure Event Hubs для Java, включая отправку и получение событий, пакетную обработку и готовые к использованию в производственной среде процессоры событий.
...Расширить всеSDK Azure Event Hubs для Java
Создавайте приложения для потоковой передачи данных в режиме реального времени с помощью SDK Azure Event Hubs для Java.
Установка
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("Order created");
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", // partitionId
10, // maxEvents
EventPosition.earliest(), // startingPosition
Duration.ofSeconds(30) // timeout
);
for (PartitionEvent partitionEvent : events) {
EventData event = partitionEvent.getData();
System.out.println("Тело: " + event.getBodyAsString());
System.out.println("Sequence: " + event.getSequenceNumber());
System.out.println("Offset: " + 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
// Получить информацию о хабе
EventHubProperties hubProps = producer.getEventHubProperties();
System.out.println("Хаб: " + hubProps.getName());
System.out.println("Партиции: " + hubProps.getPartitionIds());
// Получение информации о разделе
PartitionProperties partitionProps = producer.getPartitionProperties("0");
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
Копировать





Дом
