azure-eventhub-java
microsoft/skills
Java용 Azure Event Hubs SDK를 사용하여 이벤트 송수신, 일괄 처리, 운영 환경에 적합한 이벤트 프로세서 등을 포함한 실시간 스트리밍 애플리케이션을 구축하세요.
...모든 것을 확장하십시오Java용 Azure Event Hubs SDK
Java용 Azure Event Hubs SDK를 사용하여 실시간 스트리밍 애플리케이션을 구축하세요.
설치
com.azure
azure-messaging-eventhubs
5.19.0
com.azureazure-messaging-eventhubs
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("Partition 0 event"));
producer.send(batch);
파티션 키를 사용하여 전송
CreateBatchOptions options = new CreateBatchOptions()
.setPartitionKey("customer-123");
EventDataBatch batch = producer.createBatch(options);
batch.tryAdd(new EventData("Customer event"));
producer.send(batch);
속성이 있는 이벤트
EventData event = new EventData("주문 생성");
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", // 파티션 ID
10, // 최대 이벤트 수
EventPosition.earliest(), // 시작 위치
Duration.ofSeconds(30) // 타임아웃
);
for (PartitionEvent partitionEvent : events) {
EventData event = partitionEvent.getData();
System.out.println("본문: " + event.getBodyAsString());
System.out.println("시퀀스: " + event.getSequenceNumber());
System.out.println("오프셋: " + 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("Error: " + 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("완료")
);
이벤트 허브 속성 가져오기
// 허브 정보 가져오기
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"
- "이벤트 허브 프로듀서/컨슈머"
- "파티션 처리"
---
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
복사





집
