azure-eventgrid-java
microsoft/skills
Créez des applications événementielles à l'aide du SDK Azure Event Grid pour Java, y compris la publication et la réception d'événements avec EventGridEvent, CloudEvent et des schémas personnalisés.
...Développer toutSDK Azure Event Grid pour Java
Créez des applications événementielles à l'aide du SDK Azure Event Grid pour Java.
Installation
<dependency><groupid>com.azure</groupid><artifactid>azure-messaging-eventgrid</artifactid><version>4.27.0</version></dependency>Création du client
EventGridPublisherClient
import com.azure.messaging.eventgrid.EventGridPublisherClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
// Avec clé d'API
EventGridPublisherClient<eventgridevent> client = new EventGridPublisherClientBuilder()
.endpoint("<topic-endpoint>")
.credential(new AzureKeyCredential("<access-key>"))
.buildEventGridEventPublisherClient();
// Pour CloudEvents
EventGridPublisherClient<cloudevent> cloudClient = new EventGridPublisherClientBuilder()
.endpoint("<topic-endpoint>")
.credential(new AzureKeyCredential("<access-key>"))
.buildCloudEventPublisherClient();
</access-key></topic-endpoint></cloudevent></access-key></topic-endpoint></eventgridevent>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=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
.requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
.build();
// Ou utilisez un identifiant spécifique directement en production :
// Voir https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();
EventGridPublisherClient<eventgridevent> client = new EventGridPublisherClientBuilder()
.endpoint("<topic-endpoint>")
.credential(credential)
.buildEventGridEventPublisherClient();
</topic-endpoint></eventgridevent></specific_credential>Client asynchrone
import com.azure.messaging.eventgrid.EventGridPublisherAsyncClient;
EventGridPublisherAsyncClient<eventgridevent> asyncClient = new EventGridPublisherClientBuilder()
.endpoint("<topic-endpoint>")
.credential(new AzureKeyCredential("<access-key>"))
.buildEventGridEventPublisherAsyncClient();
</access-key></topic-endpoint></eventgridevent>Types d'événements
| Type | Description |
|---|---|
| `EventGridEvent` | Schéma natif d'Azure Event Grid |
| `CloudEvent` | Spécification CNCF CloudEvents 1.0 |
| `BinaryData` | Événements de schéma personnalisé |
Modèles principaux
Publier un EventGridEvent
import com.azure.messaging.eventgrid.EventGridEvent;
import com.azure.core.util.BinaryData;
EventGridEvent event = new EventGridEvent(
"resource/path", // sujet
"MyApp.Events.OrderCreated", // type d'événement
BinaryData.fromObject(new OrderData("order-123", 99.99)), // données
"1.0" // version des données
);
client.sendEvent(event);
Publier plusieurs événements
List<eventgridevent> events = Arrays.asList(
new EventGridEvent("orders/1", "Order.Created",
BinaryData.fromObject(order1), "1.0"),
new EventGridEvent("orders/2", "Order.Created",
BinaryData.fromObject(order2), "1.0")
);
client.sendEvents(events);
</eventgridevent>Publier un CloudEvent
import com.azure.core.models.CloudEvent;
import com.azure.core.models.CloudEventDataFormat;
CloudEvent cloudEvent = new CloudEvent(
"/myapp/orders", // source
"order.created", // type
BinaryData.fromObject(orderData), // données
CloudEventDataFormat.JSON // format des données
);
cloudEvent.setSubject("orders/12345");
cloudEvent.setId(UUID.randomUUID().toString());
cloudClient.sendEvent(cloudEvent);
Publier un lot de CloudEvents
List<cloudevent> cloudEvents = Arrays.asList(
new CloudEvent("/app", "event.type1", BinaryData.fromString("data1"), CloudEventDataFormat.JSON),
new CloudEvent("/app", "event.type2", BinaryData.fromString("data2"), CloudEventDataFormat.JSON)
);
cloudClient.sendEvents(cloudEvents);
</cloudevent>Publication asynchrone
asyncClient.sendEvent(event)
.subscribe(
unused -> System.out.println("Événement envoyé avec succès"),
error -> System.err.println("Erreur : " + error.getMessage())
);
// Avec plusieurs événements
asyncClient.sendEvents(events)
.doOnSuccess(unused -> System.out.println("Tous les événements envoyés"))
.doOnError(error -> System.err.println("Échec : " + error))
.block(); // Bloquer si nécessaire
Classe de données d'événement personnalisée
public class OrderData {
private String orderId;
private double amount;
private String customerId;
public OrderData(String orderId, double amount) {
this.orderId = orderId;
this.amount = amount;
}
// Getters et setters
}
// Utilisation
OrderData order = new OrderData("ORD-123", 150.00);
EventGridEvent event = new EventGridEvent(
"orders/" + order.getOrderId(),
"MyApp.Order.Created",
BinaryData.fromObject(order),
"1.0"
);
Réception d'événements
Analyser un EventGridEvent
import com.azure.messaging.eventgrid.EventGridEvent;
// À partir d'une chaîne JSON (par exemple, charge utile webhook)
String jsonPayload = "[{\"id\": \"...\", ...}]";
List<eventgridevent> events = EventGridEvent.fromString(jsonPayload);
for (EventGridEvent event : events) {
System.out.println("Type d'événement : " + event.getEventType());
System.out.println("Sujet : " + event.getSubject());
System.out.println("Heure de l'événement : " + event.getEventTime());
// Obtenir les données
BinaryData data = event.getData();
OrderData orderData = data.toObject(OrderData.class);
}
</eventgridevent>Analyser un CloudEvent
import com.azure.core.models.CloudEvent;
String cloudEventJson = "[{\"specversion\": \"1.0\", ...}]";
List<cloudevent> cloudEvents = CloudEvent.fromString(cloudEventJson);
for (CloudEvent event : cloudEvents) {
System.out.println("Type : " + event.getType());
System.out.println("Source : " + event.getSource());
System.out.println("ID : " + event.getId());
MyEventData data = event.getData().toObject(MyEventData.class);
}
</cloudevent>Gérer les événements système
import com.azure.messaging.eventgrid.systemevents.*;
for (EventGridEvent event : events) {
if (event.getEventType().equals("Microsoft.Storage.BlobCreated")) {
StorageBlobCreatedEventData blobData =
event.getData().toObject(StorageBlobCreatedEventData.class);
System.out.println("URL du blob : " + blobData.getUrl());
}
}
Espaces de noms Event Grid (MQTT/Retrait)
Recevoir depuis le sujet de l'espace de noms
import com.azure.messaging.eventgrid.namespaces.EventGridReceiverClient;
import com.azure.messaging.eventgrid.namespaces.EventGridReceiverClientBuilder;
import com.azure.messaging.eventgrid.namespaces.models.*;
EventGridReceiverClient receiverClient = new EventGridReceiverClientBuilder()
.endpoint("<namespace-endpoint>")
.credential(new AzureKeyCredential("<key>"))
.topicName("my-topic")
.subscriptionName("my-subscription")
.buildClient();
// Recevoir des événements
ReceiveResult result = receiverClient.receive(10, Duration.ofSeconds(30));
for (ReceiveDetails detail : result.getValue()) {
CloudEvent event = detail.getEvent();
System.out.println("Événement : " + event.getType());
// Accuser réception de l'événement
receiverClient.acknowledge(Arrays.asList(detail.getBrokerProperties().getLockToken()));
}
</key></namespace-endpoint>Rejeter ou libérer des événements
// Rejeter (ne pas réessayer)
receiverClient.reject(Arrays.asList(lockToken));
// Libérer (réessayer plus tard)
receiverClient.release(Arrays.asList(lockToken));
// Libérer avec un délai
receiverClient.release(Arrays.asList(lockToken),
new ReleaseOptions().setDelay(ReleaseDelay.BY_60_SECONDS));
Gestion des erreurs
import com.azure.core.exception.HttpResponseException;
try {
client.sendEvent(event);
} catch (HttpResponseException e) {
System.out.println("Statut : " + e.getResponse().getStatusCode());
System.out.println("Erreur : " + e.getMessage());
}
Variables d'environnement
EVENT_GRID_TOPIC_ENDPOINT=https://<topic-name>.<region>.eventgrid.azure.net/api/events # Requis pour toutes les méthodes d'authentification
EVENT_GRID_ACCESS_KEY=<your-access-key> # Requis uniquement pour l'authentification AzureKeyCredential
AZURE_TOKEN_CREDENTIALS=prod # Requis uniquement si DefaultAzureCredential est utilisé en production
</your-access-key></region></topic-name>Meilleures pratiques
- Regrouper les événements : Envoyer plusieurs événements en un seul appel si possible
- Idempotence : Inclure des IDs d'événement uniques pour la déduplication
- Validation du schéma : Utiliser des classes de données d'événement fortement typées
- Logique de retry : Intégrée, mais envisager une file d'attente de lettres mortes pour les échecs
- Taille des événements : Garder les événements en dessous de 1 Mo (64 Ko pour l'offre de base)
Mots déclencheurs
- "Event Grid Java"
- "publier des événements Azure"
- "SDK CloudEvent"
- "messagerie événementielle"
- "pub/sub Azure"
- "événements webhook"
---
name: azure-eventgrid-java
description: Build event-driven applications using the Azure Event Grid SDK for Java, including publishing and receiving events with EventGridEvent, CloudEvent, and custom schemas.
license: MIT
---
# Azure Event Grid SDK for Java
Build event-driven applications using the Azure Event Grid SDK for Java.
## Installation
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventgrid</artifactId>
<version>4.27.0</version>
</dependency>
```
## Client Creation
### EventGridPublisherClient
```java
import com.azure.messaging.eventgrid.EventGridPublisherClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
// With API Key
EventGridPublisherClient<EventGridEvent> client = new EventGridPublisherClientBuilder()
.endpoint("<topic-endpoint>")
.credential(new AzureKeyCredential("<access-key>"))
.buildEventGridEventPublisherClient();
// For CloudEvents
EventGridPublisherClient<CloudEvent> cloudClient = new EventGridPublisherClientBuilder()
.endpoint("<topic-endpoint>")
.credential(new AzureKeyCredential("<access-key>"))
.buildCloudEventPublisherClient();
```
### 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();
EventGridPublisherClient<EventGridEvent> client = new EventGridPublisherClientBuilder()
.endpoint("<topic-endpoint>")
.credential(credential)
.buildEventGridEventPublisherClient();
```
### Async Client
```java
import com.azure.messaging.eventgrid.EventGridPublisherAsyncClient;
EventGridPublisherAsyncClient<EventGridEvent> asyncClient = new EventGridPublisherClientBuilder()
.endpoint("<topic-endpoint>")
.credential(new AzureKeyCredential("<access-key>"))
.buildEventGridEventPublisherAsyncClient();
```
## Event Types
| Type | Description |
|------|-------------|
| `EventGridEvent` | Azure Event Grid native schema |
| `CloudEvent` | CNCF CloudEvents 1.0 specification |
| `BinaryData` | Custom schema events |
## Core Patterns
### Publish EventGridEvent
```java
import com.azure.messaging.eventgrid.EventGridEvent;
import com.azure.core.util.BinaryData;
EventGridEvent event = new EventGridEvent(
"resource/path", // subject
"MyApp.Events.OrderCreated", // eventType
BinaryData.fromObject(new OrderData("order-123", 99.99)), // data
"1.0" // dataVersion
);
client.sendEvent(event);
```
### Publish Multiple Events
```java
List<EventGridEvent> events = Arrays.asList(
new EventGridEvent("orders/1", "Order.Created",
BinaryData.fromObject(order1), "1.0"),
new EventGridEvent("orders/2", "Order.Created",
BinaryData.fromObject(order2), "1.0")
);
client.sendEvents(events);
```
### Publish CloudEvent
```java
import com.azure.core.models.CloudEvent;
import com.azure.core.models.CloudEventDataFormat;
CloudEvent cloudEvent = new CloudEvent(
"/myapp/orders", // source
"order.created", // type
BinaryData.fromObject(orderData), // data
CloudEventDataFormat.JSON // dataFormat
);
cloudEvent.setSubject("orders/12345");
cloudEvent.setId(UUID.randomUUID().toString());
cloudClient.sendEvent(cloudEvent);
```
### Publish CloudEvents Batch
```java
List<CloudEvent> cloudEvents = Arrays.asList(
new CloudEvent("/app", "event.type1", BinaryData.fromString("data1"), CloudEventDataFormat.JSON),
new CloudEvent("/app", "event.type2", BinaryData.fromString("data2"), CloudEventDataFormat.JSON)
);
cloudClient.sendEvents(cloudEvents);
```
### Async Publishing
```java
asyncClient.sendEvent(event)
.subscribe(
unused -> System.out.println("Event sent successfully"),
error -> System.err.println("Error: " + error.getMessage())
);
// With multiple events
asyncClient.sendEvents(events)
.doOnSuccess(unused -> System.out.println("All events sent"))
.doOnError(error -> System.err.println("Failed: " + error))
.block(); // Block if needed
```
### Custom Event Data Class
```java
public class OrderData {
private String orderId;
private double amount;
private String customerId;
public OrderData(String orderId, double amount) {
this.orderId = orderId;
this.amount = amount;
}
// Getters and setters
}
// Usage
OrderData order = new OrderData("ORD-123", 150.00);
EventGridEvent event = new EventGridEvent(
"orders/" + order.getOrderId(),
"MyApp.Order.Created",
BinaryData.fromObject(order),
"1.0"
);
```
## Receiving Events
### Parse EventGridEvent
```java
import com.azure.messaging.eventgrid.EventGridEvent;
// From JSON string (e.g., webhook payload)
String jsonPayload = "[{\"id\": \"...\", ...}]";
List<EventGridEvent> events = EventGridEvent.fromString(jsonPayload);
for (EventGridEvent event : events) {
System.out.println("Event Type: " + event.getEventType());
System.out.println("Subject: " + event.getSubject());
System.out.println("Event Time: " + event.getEventTime());
// Get data
BinaryData data = event.getData();
OrderData orderData = data.toObject(OrderData.class);
}
```
### Parse CloudEvent
```java
import com.azure.core.models.CloudEvent;
String cloudEventJson = "[{\"specversion\": \"1.0\", ...}]";
List<CloudEvent> cloudEvents = CloudEvent.fromString(cloudEventJson);
for (CloudEvent event : cloudEvents) {
System.out.println("Type: " + event.getType());
System.out.println("Source: " + event.getSource());
System.out.println("ID: " + event.getId());
MyEventData data = event.getData().toObject(MyEventData.class);
}
```
### Handle System Events
```java
import com.azure.messaging.eventgrid.systemevents.*;
for (EventGridEvent event : events) {
if (event.getEventType().equals("Microsoft.Storage.BlobCreated")) {
StorageBlobCreatedEventData blobData =
event.getData().toObject(StorageBlobCreatedEventData.class);
System.out.println("Blob URL: " + blobData.getUrl());
}
}
```
## Event Grid Namespaces (MQTT/Pull)
### Receive from Namespace Topic
```java
import com.azure.messaging.eventgrid.namespaces.EventGridReceiverClient;
import com.azure.messaging.eventgrid.namespaces.EventGridReceiverClientBuilder;
import com.azure.messaging.eventgrid.namespaces.models.*;
EventGridReceiverClient receiverClient = new EventGridReceiverClientBuilder()
.endpoint("<namespace-endpoint>")
.credential(new AzureKeyCredential("<key>"))
.topicName("my-topic")
.subscriptionName("my-subscription")
.buildClient();
// Receive events
ReceiveResult result = receiverClient.receive(10, Duration.ofSeconds(30));
for (ReceiveDetails detail : result.getValue()) {
CloudEvent event = detail.getEvent();
System.out.println("Event: " + event.getType());
// Acknowledge the event
receiverClient.acknowledge(Arrays.asList(detail.getBrokerProperties().getLockToken()));
}
```
### Reject or Release Events
```java
// Reject (don't retry)
receiverClient.reject(Arrays.asList(lockToken));
// Release (retry later)
receiverClient.release(Arrays.asList(lockToken));
// Release with delay
receiverClient.release(Arrays.asList(lockToken),
new ReleaseOptions().setDelay(ReleaseDelay.BY_60_SECONDS));
```
## Error Handling
```java
import com.azure.core.exception.HttpResponseException;
try {
client.sendEvent(event);
} catch (HttpResponseException e) {
System.out.println("Status: " + e.getResponse().getStatusCode());
System.out.println("Error: " + e.getMessage());
}
```
## Environment Variables
```bash
EVENT_GRID_TOPIC_ENDPOINT=https://<topic-name>.<region>.eventgrid.azure.net/api/events # Required for all auth methods
EVENT_GRID_ACCESS_KEY=<your-access-key> # Only required for AzureKeyCredential auth
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Best Practices
1. **Batch Events**: Send multiple events in one call when possible
2. **Idempotency**: Include unique event IDs for deduplication
3. **Schema Validation**: Use strongly-typed event data classes
4. **Retry Logic**: Built-in, but consider dead-letter for failures
5. **Event Size**: Keep events under 1MB (64KB for basic tier)
## Trigger Phrases
- "Event Grid Java"
- "publish events Azure"
- "CloudEvent SDK"
- "event-driven messaging"
- "pub/sub Azure"
- "webhook events"
Tous les fichiers
0 fichiersInstaller azure-eventgrid-java
Téléchargez et extrayez les fichiers de compétences dans votre répertoire .claude/skills/.
Télécharger le ZIPClonez 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-eventgrid-java # Copy SKILL.md to your .claude/skills/ directory
Copier





Maison
