azure-eventgrid-java
This library allows Java developers to send and receive events across Azure services using a publish-subscribe pattern.
Install
mkdir -p .claude/skills/azure-eventgrid-java && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/5509" && unzip -o skill.zip -d .claude/skills/azure-eventgrid-java && rm skill.zipInstalls to .claude/skills/azure-eventgrid-java
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Build event-driven applications with Azure Event Grid SDK for Java. Use when publishing events, implementing pub/sub patterns, or integrating with Azure services via events.Key capabilities
- →Publish events to Azure Event Grid
- →Support CloudEvents 1.0 specification
- →Implement asynchronous event publishing
- →Handle system events from Azure services
- →Manage namespace topics and subscriptions
How it works
The SDK provides clients to send and receive events using either native Event Grid or CloudEvent schemas, supporting both synchronous and asynchronous patterns.
Inputs & outputs
When to use azure-eventgrid-java
- →Publishing events to Event Grid
- →Implementing pub/sub logic
- →Integrating Azure services
About this skill
Azure Event Grid SDK for Java
Build event-driven applications using the Azure Event Grid SDK for Java.
Installation
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventgrid</artifactId>
<version>4.27.0</version>
</dependency>
Client Creation
EventGridPublisherClient
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
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
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
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
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
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
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
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
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
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
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
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
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
// 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
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
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
- Batch Events: Send multiple events in one call when possible
- Idempotency: Include unique event IDs for deduplication
- Schema Validation: Use strongly-typed event data classes
- Retry Logic: Built-in, but consider dead-letter for failures
- 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"
When not to use it
- →Non-Azure event-driven architectures
- →High-latency synchronous messaging
Prerequisites
Limitations
- →Event size limit of 1MB
- →Requires Azure infrastructure
How it compares
It provides a strongly-typed Java interface for Azure-native messaging, abstracting the underlying HTTP/REST complexity.
Compared to similar skills
azure-eventgrid-java side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| azure-eventgrid-java (this skill) | 3 | 3mo | Review | Intermediate |
| springboot-patterns | 11 | 5mo | No flags | Intermediate |
| azure-communication-chat-java | 1 | 3mo | Review | Intermediate |
| azure-appconfiguration-java | 1 | 3mo | Review | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by microsoft
View all by microsoft →You might also like
springboot-patterns
affaan-m
Spring Boot 架构模式、REST API 设计、分层服务、数据访问、缓存、异步处理和日志记录。适用于 Java Spring Boot 后端工作。
azure-communication-chat-java
microsoft
Build real-time chat applications with Azure Communication Services Chat Java SDK. Use when implementing chat threads, messaging, participants, read receipts, typing notifications, or real-time chat features.
azure-appconfiguration-java
microsoft
Azure App Configuration SDK for Java. Centralized application configuration management with key-value settings, feature flags, and snapshots. Triggers: "ConfigurationClient java", "app configuration java", "feature flag java", "configuration setting java", "azure config java".
azure-communication-sms-java
microsoft
Send SMS messages with Azure Communication Services SMS Java SDK. Use when implementing SMS notifications, alerts, OTP delivery, bulk messaging, or delivery reports.
generating-rest-apis
jeremylongshore
Generate complete REST API implementations from OpenAPI specifications or database schemas. Use when generating RESTful API implementations. Trigger with phrases like "generate REST API", "create RESTful API", or "build REST endpoints".
slack-bot-builder
davila7
Build Slack apps using the Bolt framework across Python, JavaScript, and Java. Covers Block Kit for rich UIs, interactive components, slash commands, event handling, OAuth installation flows, and Workflow Builder integration. Focus on best practices for production-ready Slack apps. Use when: slack bot, slack app, bolt framework, block kit, slash command.