azure-eventhub-java

द्वारा microsoft

Build real-time streaming applications with Azure Event Hubs SDK for Java. Use when implementing event streaming, high-throughput data ingestion, or building event-driven architectures.

npx skills add https://github.com/microsoft/skills --skill azure-eventhub-java

Azure Event Hubs SDK for Java

Build real-time streaming applications using the Azure Event Hubs SDK for Java.

Installation

<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

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

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

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

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

import com.azure.messaging.eventhubs.EventData;

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

Send Event Batch

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

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

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

EventDataBatch batch = producer.createBatch(options);
batch.tryAdd(new EventData("Customer event"));
producer.send(batch);

Event with Properties

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)

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)

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

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

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

// 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

// 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

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

// 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

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"

microsoft की और Skills

oss-growth
microsoft
OSS ग्रोथ हैकर व्यक्तित्व
agent-framework-azure-ai-py
microsoft
Microsoft Agent Framework Python SDK (agent-framework-azure-ai) का उपयोग करके Azure AI Foundry एजेंट बनाएं। AzureAIAgentsProvider के साथ स्थायी एजेंट बनाते समय, होस्टेड टूल्स (कोड इंटरप्रेटर, फ़ाइल खोज, वेब खोज) का उपयोग करते समय, MCP सर्वर एकीकृत करते समय, वार्तालाप थ्रेड प्रबंधित करते समय, या स्ट्रीमिंग प्रतिक्रियाएँ लागू करते समय उपयोग करें। फ़ंक्शन टूल्स, संरचित आउटपुट और मल्टी-टूल एजेंट शामिल हैं।
development
airunway-aks-setup
microsoft
AI Runway को AKS पर सेट करें — बेयर क्लस्टर से चल रहे मॉडल तक। इसमें क्लस्टर सत्यापन, कंट्रोलर इंस्टॉल, GPU मूल्यांकन, प्रोवाइडर सेटअप, और पहली डिप्लॉयमेंट शामिल है। कब: "setup AI Runway", "onboard AKS cluster", "install AI Runway", "airunway setup", "deploy model to AKS", "GPU inference on AKS", "KAITO setup on AKS", "run LLM on AKS", "vLLM on AKS", "set up model serving on AKS", "AI Runway controller"।
devops
appinsights-instrumentation
microsoft
Azure Application Insights के साथ वेबऐप्स को इंस्ट्रूमेंट करने के लिए मार्गदर्शन। टेलीमेट्री पैटर्न, SDK सेटअप, और कॉन्फ़िगरेशन संदर्भ प्रदान करता है। WHEN: ऐप को कैसे इंस्ट्रूमेंट करें, App Insights SDK, टेलीमेट्री पैटर्न, App Insights क्या है, Application Insights मार्गदर्शन, इंस्ट्रूमेंटेशन उदाहरण, APM सर्वोत्तम अभ्यास।
devops
applicationinsights-web-ts
microsoft
ब्राउज़र/वेब ऐप्स को Application Insights JavaScript SDK (@microsoft/applicationinsights-web) से इंस्ट्रूमेंट करें। Real User Monitoring (RUM) के लिए उपयोग करें — पेज व्यू, क्लिक, AJAX/fetch निर्भरताएँ, अपवाद, कस्टम इवेंट, और बैकएंड OpenTelemetry ट्रेस से सहसंबंधित ब्राउज़र-साइड GenAI एजेंट ट्रेस। SDK Loader Script और npm सेटअप, फ्रेमवर्क एक्सटेंशन (React, React Native, Angular), Click Analytics, टेलीमेट्री इनिशियलाइज़र, और ब्राउज़र से उत्सर्जित एजेंट/टूल/मॉडल स्पैन के लिए OTel GenAI सिमेंटिक कन्वेंशन शामिल हैं।
devops
azure-ai-anomalydetector-java
microsoft
Azure AI Anomaly Detector SDK for Java के साथ एनोमली डिटेक्शन एप्लिकेशन बनाएं। यूनीवेरिएट/मल्टीवेरिएट एनोमली डिटेक्शन, टाइम-सीरीज़ विश्लेषण, या AI-संचालित मॉनिटरिंग लागू करते समय उपयोग करें।
development
azure-ai-language-conversations-py
microsoft
<text> azure-ai-language-conversations Python SDK का उपयोग करके संवादात्मक भाषा समझ (CLU) लागू करें। ConversationAnalysisClient के साथ काम करते समय उपयोग करें ताकि वार्तालाप के इरादे और संस्थाओं का विश्लेषण किया जा सके, NLP सुविधाएँ बनाई जा सकें, या अनुप्रयोगों में भाषा समझ को एकीकृत किया जा सके। </text>
development
azure-ai-ml-py
microsoft
Azure Machine Learning SDK v2 for Python। ML वर्कस्पेस, जॉब्स, मॉडल, डेटासेट, कंप्यूट और पाइपलाइन के लिए उपयोग करें। ट्रिगर्स: "azure-ai-ml", "MLClient", "workspace", "model registry", "training jobs", "datasets"।
development