option
MaisonMaison Skill Outils de développement azure-eventhub-java

azure-eventhub-java

microsoft/skills microsoft/skills

Créez des applications de streaming en temps réel à l'aide du SDK Azure Event Hubs pour Java, notamment pour l'envoi et la réception d'événements, le traitement par lots et les processeurs d'événements prêts pour la production.

...Développer tout
8
Heure mise à jour 12 septembre 2026

SDK Azure Event Hubs pour Java

Créez des applications de streaming en temps réel à l'aide du SDK Azure Event Hubs pour Java.

Installation


    com.azure
    azure-messaging-eventhubs
    5.19.0




    com.azure
    azure-messaging-eventhubs-checkpointstore-blob
    1.20.0

Création d'un client

EventHubProducerClient

import com.azure.messaging.eventhubs.EventHubProducerClient;
import com.azure.messaging.eventhubs.EventHubClientBuilder;

// Avec une chaîne de connexion
EventHubProducerClient producer = new EventHubClientBuilder()
    .connectionString("", "")
    .buildProducerClient();

// Chaîne de connexion complète avec EntityPath
EventHubProducerClient producer = new EventHubClientBuilder()
    .connectionString("")
    .buildProducerClient();

Avec DefaultAzureCredential

import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

// Développement local : DefaultAzureCredential. Production : définissez AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=
TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Ou utilisez directement des informations d'identification spécifiques en production :
// Voir 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();

Clients asynchrones

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();

Modèles de base

Envoyer un événement unique

import com.azure.messaging.eventhubs.EventData;

EventData eventData = new EventData("Bonjour, Event Hubs !");
producer.send(Collections.singletonList(eventData));

Envoyer un lot d’événements

import com.azure.messaging.eventhubs.EventDataBatch;
import com.azure.messaging.eventhubs.models.CreateBatchOptions;

// Créer un lot
EventDataBatch batch = producer.createBatch();

// Ajouter des événements (renvoie false si le lot est plein)
for (int i = 0; i < 100; i++) {
    EventData event = new EventData("Événement " + i);
    if (!batch.tryAdd(event)) {
        // Le lot est plein, envoyer et créer un nouveau lot
        producer.send(batch);
        batch = producer.createBatch();
        batch.tryAdd(event);
    }
}

// Envoyer les événements restants
if (batch.getCount() > 0) {
    producer.send(batch);
}

Envoi vers une partition spécifique

CreateBatchOptions options = new CreateBatchOptions()
    .setPartitionId("0");

EventDataBatch batch = producer.createBatch(options);
batch.tryAdd(new EventData("Événement de la partition 0"));
producer.send(batch);

Envoi avec une clé de partition

CreateBatchOptions options = new CreateBatchOptions()
    .setPartitionKey("client-123");

EventDataBatch batch = producer.createBatch(options);
batch.tryAdd(new EventData("Événement client"));
producer.send(batch);

Événement avec propriétés

EventData event = new EventData("Commande créée");
event.getProperties().put("orderId", "ORD-123");
event.getProperties().put("customerId", "CUST-456");
event.getProperties().put("priority", 1);

producer.send(Collections.singletonList(event));

Réception d’événements (simple)

import com.azure.messaging.eventhubs.models.EventPosition;
import com.azure.messaging.eventhubs.models.PartitionEvent;

// Réception à partir d’une partition spécifique
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("Corps : " + event.getBodyAsString());
    System.out.println("Séquence : " + event.getSequenceNumber());
    System.out.println("Décalage : " + event.getOffset());
}

EventProcessorClient (Production)

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;

// Créer un magasin de points de contrôle
BlobContainerAsyncClient blobClient = new BlobContainerClientBuilder()
    .connectionString("")
    .containerName("checkpoints")
    .buildAsyncClient();

// Créer un processeur
EventProcessorClient processor = new EventProcessorClientBuilder()
    .connectionString("", "")
    .consumerGroup("$Default")
    .checkpointStore(new BlobCheckpointStore(blobClient))
    .processEvent(eventContext -> {
        EventData event = eventContext.getEventData();
        System.out.println("Traitement : " + event.getBodyAsString());
        
        // Enregistrement d'un point de contrôle après le traitement
        eventContext.updateCheckpoint();
    })
    .processError(errorContext -> {
        System.err.println("Erreur : " + errorContext.getThrowable().getMessage());
        System.err.println("Partition : " + errorContext.getPartitionContext().getPartitionId());
    })
    .buildEventProcessorClient();

// Lancer le traitement
processor.start();

// Laisser tourner...
Thread.sleep(Duration.ofMinutes(5).toMillis());

// Arrêter proprement
processor.stop();

Traitement par lots

EventProcessorClient processor = new EventProcessorClientBuilder()
    .connectionString("", "")
    .consumerGroup("$Default")
    .checkpointStore(new BlobCheckpointStore(blobClient))
    .processEventBatch(eventBatchContext -> {
        List events = eventBatchContext.getEvents();
        System.out.printf("%d événements reçus%n", events.size());
        
        for (EventData event : events) {
            // Traiter chaque événement
            System.out.println(event.getBodyAsString());
        }
        
        // Point de contrôle après le lot
        eventBatchContext.updateCheckpoint();
    }, 50) // maxBatchSize
    .processError(errorContext -> {
        System.err.println("Erreur : " + errorContext.getThrowable());
    })
    .buildEventProcessorClient();

Réception asynchrone

asyncConsumer.receiveFromPartition("0", EventPosition.latest())
    .subscribe(
        partitionEvent -> {
            EventData event = partitionEvent.getData();
            System.out.println("Reçu : " + event.getBodyAsString());
        },
        error -> System.err.println("Erreur : " + error),
        () -> System.out.println("Terminé")
    );

Récupération des propriétés de l’Event Hub

// Récupérer les informations sur le hub
EventHubProperties hubProps = producer.getEventHubProperties();
System.out.println("Hub : " + hubProps.getName());
System.out.println("Partitions : " + hubProps.getPartitionIds());

// Récupérer les informations sur la partition
PartitionProperties partitionProps = producer.getPartitionProperties("0");
System.out.println("Début de la séquence : " + partitionProps.getBeginningSequenceNumber());
System.out.println("Dernière séquence : " + partitionProps.getLastEnqueuedSequenceNumber());
System.out.println("Dernier décalage : " + partitionProps.getLastEnqueuedOffset());

Positions des événements

// Commencer par le début
EventPosition.earliest()

// Commencer par la fin (nouveaux événements uniquement)
EventPosition.latest()

// À partir d’un décalage spécifique
EventPosition.fromOffset(12345L)

// À partir d’un numéro de séquence spécifique
EventPosition.fromSequenceNumber(100L)

// À partir d’une heure spécifique
EventPosition.fromEnqueuedTime(Instant.now().minus(Duration.ofHours(1)))

Gestion des erreurs

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("Erreur transitoire, nouvelle tentative");
        }
    }
    
    System.err.printf("Erreur sur la partition %s : %s%n", partitionId, error.getMessage());
})

Nettoyage des ressources

// Toujours fermer les clients
try {
    producer.send(batch);
} finally {
    producer.close();
}

// Ou utiliser « try-with-resources »
try (EventHubProducerClient producer = new EventHubClientBuilder()
        .connectionString(connectionString, eventHubName)
        .buildProducerClient()) {
    producer.send(events);
}

Variables d’environnement

EVENT_HUBS_CONNECTION_STRING=Endpoint=sb://.servicebus.windows.net/;SharedAccessKeyName=...  # Alternative à l’authentification par Entra ID
EVENT_HUBS_NAME= # Obligatoire pour le nom de l'Event Hub
STORAGE_CONNECTION_STRING= # Alternative à l'authentification par Entra ID pour la mise en cache
AZURE_TOKEN_CREDENTIALS=prod  # Obligatoire uniquement si DefaultAzureCredential est utilisé en production

Bonnes pratiques

  1. Utilisez EventProcessorClient: en production, il assure l’équilibrage de charge et la mise en point d’arrêt
  2. Événements par lots: utilisez EventDataBatch pour un envoi efficace
  3. Clés de partition: à utiliser pour garantir l’ordre au sein d’une partition
  4. Points de contrôle: effectuez un point de contrôle après le traitement pour éviter tout retraitement
  5. Gestion des erreurs: gérez les erreurs transitoires à l’aide de tentatives de réessai
  6. Fermer les clients: fermez toujours les producteurs/consommateurs une fois l'opération terminée

Expressions clés

  • « Event Hubs Java »
  • « streaming d'événements Azure »
  • « ingestion de données en temps réel »
  • « EventProcessorClient »
  • « producteur-consommateur Event Hubs »
  • « traitement par partition »
Voir sur GitHub
---
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"

Tous les fichiers

0 fichiers

Installer azure-eventhub-java

Téléchargez et décompressez les fichiers de compétences dans votre répertoire .claude/skills/.

Télécharger le ZIP

Clonez le dépôt et copiez les fichiers de compétence dans votre projet.

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

Copier Copier
Configuration rapide: Copiez le dossier de la compétence dans .claude/skills/ Claude détectera et utilisera automatiquement cette compétence

Compétences similaires

algorithmic-art
Heure mise à jour 27 août 2026
receiving-code-review
Heure mise à jour 3 septembre 2026
tech-debt-tracker
Heure mise à jour 29 août 2026
senior-backend
Heure mise à jour 30 août 2026
OR