[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-acfd24ee-2ce6-46e4-9677-77638ff19dfe":3,"$fH3FazCYUbWTUvfLdaq2p8Or53s3_MjpKk15-bVSH_Jw":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"acfd24ee-2ce6-46e4-9677-77638ff19dfe","azure-eventhub-java","使用 Azure Event Hubs SDK for Java 构建实时流应用程序。在实现事件流、高吞吐量数据摄取或构建事件驱动架构时使用。","cat_coding_devops","mod_coding","sickn33,coding","---\nname: azure-eventhub-java\ndescription: \"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.\"\nrisk: unknown\nsource: community\ndate_added: \"2026-02-27\"\n---\n\n# Azure Event Hubs SDK for Java\n\nBuild real-time streaming applications using the Azure Event Hubs SDK for Java.\n\n## Installation\n\n```xml\n\u003Cdependency>\n    \u003CgroupId>com.azure\u003C\u002FgroupId>\n    \u003CartifactId>azure-messaging-eventhubs\u003C\u002FartifactId>\n    \u003Cversion>5.19.0\u003C\u002Fversion>\n\u003C\u002Fdependency>\n\n\u003C!-- For checkpoint store (production) -->\n\u003Cdependency>\n    \u003CgroupId>com.azure\u003C\u002FgroupId>\n    \u003CartifactId>azure-messaging-eventhubs-checkpointstore-blob\u003C\u002FartifactId>\n    \u003Cversion>1.20.0\u003C\u002Fversion>\n\u003C\u002Fdependency>\n```\n\n## Client Creation\n\n### EventHubProducerClient\n\n```java\nimport com.azure.messaging.eventhubs.EventHubProducerClient;\nimport com.azure.messaging.eventhubs.EventHubClientBuilder;\n\n\u002F\u002F With connection string\nEventHubProducerClient producer = new EventHubClientBuilder()\n    .connectionString(\"\u003Cconnection-string>\", \"\u003Cevent-hub-name>\")\n    .buildProducerClient();\n\n\u002F\u002F Full connection string with EntityPath\nEventHubProducerClient producer = new EventHubClientBuilder()\n    .connectionString(\"\u003Cconnection-string-with-entity-path>\")\n    .buildProducerClient();\n```\n\n### With DefaultAzureCredential\n\n```java\nimport com.azure.identity.DefaultAzureCredentialBuilder;\n\nEventHubProducerClient producer = new EventHubClientBuilder()\n    .fullyQualifiedNamespace(\"\u003Cnamespace>.servicebus.windows.net\")\n    .eventHubName(\"\u003Cevent-hub-name>\")\n    .credential(new DefaultAzureCredentialBuilder().build())\n    .buildProducerClient();\n```\n\n### EventHubConsumerClient\n\n```java\nimport com.azure.messaging.eventhubs.EventHubConsumerClient;\n\nEventHubConsumerClient consumer = new EventHubClientBuilder()\n    .connectionString(\"\u003Cconnection-string>\", \"\u003Cevent-hub-name>\")\n    .consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)\n    .buildConsumerClient();\n```\n\n### Async Clients\n\n```java\nimport com.azure.messaging.eventhubs.EventHubProducerAsyncClient;\nimport com.azure.messaging.eventhubs.EventHubConsumerAsyncClient;\n\nEventHubProducerAsyncClient asyncProducer = new EventHubClientBuilder()\n    .connectionString(\"\u003Cconnection-string>\", \"\u003Cevent-hub-name>\")\n    .buildAsyncProducerClient();\n\nEventHubConsumerAsyncClient asyncConsumer = new EventHubClientBuilder()\n    .connectionString(\"\u003Cconnection-string>\", \"\u003Cevent-hub-name>\")\n    .consumerGroup(\"$Default\")\n    .buildAsyncConsumerClient();\n```\n\n## Core Patterns\n\n### Send Single Event\n\n```java\nimport com.azure.messaging.eventhubs.EventData;\n\nEventData eventData = new EventData(\"Hello, Event Hubs!\");\nproducer.send(Collections.singletonList(eventData));\n```\n\n### Send Event Batch\n\n```java\nimport com.azure.messaging.eventhubs.EventDataBatch;\nimport com.azure.messaging.eventhubs.models.CreateBatchOptions;\n\n\u002F\u002F Create batch\nEventDataBatch batch = producer.createBatch();\n\n\u002F\u002F Add events (returns false if batch is full)\nfor (int i = 0; i \u003C 100; i++) {\n    EventData event = new EventData(\"Event \" + i);\n    if (!batch.tryAdd(event)) {\n        \u002F\u002F Batch is full, send and create new batch\n        producer.send(batch);\n        batch = producer.createBatch();\n        batch.tryAdd(event);\n    }\n}\n\n\u002F\u002F Send remaining events\nif (batch.getCount() > 0) {\n    producer.send(batch);\n}\n```\n\n### Send to Specific Partition\n\n```java\nCreateBatchOptions options = new CreateBatchOptions()\n    .setPartitionId(\"0\");\n\nEventDataBatch batch = producer.createBatch(options);\nbatch.tryAdd(new EventData(\"Partition 0 event\"));\nproducer.send(batch);\n```\n\n### Send with Partition Key\n\n```java\nCreateBatchOptions options = new CreateBatchOptions()\n    .setPartitionKey(\"customer-123\");\n\nEventDataBatch batch = producer.createBatch(options);\nbatch.tryAdd(new EventData(\"Customer event\"));\nproducer.send(batch);\n```\n\n### Event with Properties\n\n```java\nEventData event = new EventData(\"Order created\");\nevent.getProperties().put(\"orderId\", \"ORD-123\");\nevent.getProperties().put(\"customerId\", \"CUST-456\");\nevent.getProperties().put(\"priority\", 1);\n\nproducer.send(Collections.singletonList(event));\n```\n\n### Receive Events (Simple)\n\n```java\nimport com.azure.messaging.eventhubs.models.EventPosition;\nimport com.azure.messaging.eventhubs.models.PartitionEvent;\n\n\u002F\u002F Receive from specific partition\nIterable\u003CPartitionEvent> events = consumer.receiveFromPartition(\n    \"0\",                           \u002F\u002F partitionId\n    10,                            \u002F\u002F maxEvents\n    EventPosition.earliest(),      \u002F\u002F startingPosition\n    Duration.ofSeconds(30)         \u002F\u002F timeout\n);\n\nfor (PartitionEvent partitionEvent : events) {\n    EventData event = partitionEvent.getData();\n    System.out.println(\"Body: \" + event.getBodyAsString());\n    System.out.println(\"Sequence: \" + event.getSequenceNumber());\n    System.out.println(\"Offset: \" + event.getOffset());\n}\n```\n\n### EventProcessorClient (Production)\n\n```java\nimport com.azure.messaging.eventhubs.EventProcessorClient;\nimport com.azure.messaging.eventhubs.EventProcessorClientBuilder;\nimport com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore;\nimport com.azure.storage.blob.BlobContainerAsyncClient;\nimport com.azure.storage.blob.BlobContainerClientBuilder;\n\n\u002F\u002F Create checkpoint store\nBlobContainerAsyncClient blobClient = new BlobContainerClientBuilder()\n    .connectionString(\"\u003Cstorage-connection-string>\")\n    .containerName(\"checkpoints\")\n    .buildAsyncClient();\n\n\u002F\u002F Create processor\nEventProcessorClient processor = new EventProcessorClientBuilder()\n    .connectionString(\"\u003Ceventhub-connection-string>\", \"\u003Cevent-hub-name>\")\n    .consumerGroup(\"$Default\")\n    .checkpointStore(new BlobCheckpointStore(blobClient))\n    .processEvent(eventContext -> {\n        EventData event = eventContext.getEventData();\n        System.out.println(\"Processing: \" + event.getBodyAsString());\n        \n        \u002F\u002F Checkpoint after processing\n        eventContext.updateCheckpoint();\n    })\n    .processError(errorContext -> {\n        System.err.println(\"Error: \" + errorContext.getThrowable().getMessage());\n        System.err.println(\"Partition: \" + errorContext.getPartitionContext().getPartitionId());\n    })\n    .buildEventProcessorClient();\n\n\u002F\u002F Start processing\nprocessor.start();\n\n\u002F\u002F Keep running...\nThread.sleep(Duration.ofMinutes(5).toMillis());\n\n\u002F\u002F Stop gracefully\nprocessor.stop();\n```\n\n### Batch Processing\n\n```java\nEventProcessorClient processor = new EventProcessorClientBuilder()\n    .connectionString(\"\u003Cconnection-string>\", \"\u003Cevent-hub-name>\")\n    .consumerGroup(\"$Default\")\n    .checkpointStore(new BlobCheckpointStore(blobClient))\n    .processEventBatch(eventBatchContext -> {\n        List\u003CEventData> events = eventBatchContext.getEvents();\n        System.out.printf(\"Received %d events%n\", events.size());\n        \n        for (EventData event : events) {\n            \u002F\u002F Process each event\n            System.out.println(event.getBodyAsString());\n        }\n        \n        \u002F\u002F Checkpoint after batch\n        eventBatchContext.updateCheckpoint();\n    }, 50) \u002F\u002F maxBatchSize\n    .processError(errorContext -> {\n        System.err.println(\"Error: \" + errorContext.getThrowable());\n    })\n    .buildEventProcessorClient();\n```\n\n### Async Receiving\n\n```java\nasyncConsumer.receiveFromPartition(\"0\", EventPosition.latest())\n    .subscribe(\n        partitionEvent -> {\n            EventData event = partitionEvent.getData();\n            System.out.println(\"Received: \" + event.getBodyAsString());\n        },\n        error -> System.err.println(\"Error: \" + error),\n        () -> System.out.println(\"Complete\")\n    );\n```\n\n### Get Event Hub Properties\n\n```java\n\u002F\u002F Get hub info\nEventHubProperties hubProps = producer.getEventHubProperties();\nSystem.out.println(\"Hub: \" + hubProps.getName());\nSystem.out.println(\"Partitions: \" + hubProps.getPartitionIds());\n\n\u002F\u002F Get partition info\nPartitionProperties partitionProps = producer.getPartitionProperties(\"0\");\nSystem.out.println(\"Begin sequence: \" + partitionProps.getBeginningSequenceNumber());\nSystem.out.println(\"Last sequence: \" + partitionProps.getLastEnqueuedSequenceNumber());\nSystem.out.println(\"Last offset: \" + partitionProps.getLastEnqueuedOffset());\n```\n\n## Event Positions\n\n```java\n\u002F\u002F Start from beginning\nEventPosition.earliest()\n\n\u002F\u002F Start from end (new events only)\nEventPosition.latest()\n\n\u002F\u002F From specific offset\nEventPosition.fromOffset(12345L)\n\n\u002F\u002F From specific sequence number\nEventPosition.fromSequenceNumber(100L)\n\n\u002F\u002F From specific time\nEventPosition.fromEnqueuedTime(Instant.now().minus(Duration.ofHours(1)))\n```\n\n## Error Handling\n\n```java\nimport com.azure.messaging.eventhubs.models.ErrorContext;\n\n.processError(errorContext -> {\n    Throwable error = errorContext.getThrowable();\n    String partitionId = errorContext.getPartitionContext().getPartitionId();\n    \n    if (error instanceof AmqpException) {\n        AmqpException amqpError = (AmqpException) error;\n        if (amqpError.isTransient()) {\n            System.out.println(\"Transient error, will retry\");\n        }\n    }\n    \n    System.err.printf(\"Error on partition %s: %s%n\", partitionId, error.getMessage());\n})\n```\n\n## Resource Cleanup\n\n```java\n\u002F\u002F Always close clients\ntry {\n    producer.send(batch);\n} finally {\n    producer.close();\n}\n\n\u002F\u002F Or use try-with-resources\ntry (EventHubProducerClient producer = new EventHubClientBuilder()\n        .connectionString(connectionString, eventHubName)\n        .buildProducerClient()) {\n    producer.send(events);\n}\n```\n\n## Environment Variables\n\n```bash\nEVENT_HUBS_CONNECTION_STRING=Endpoint=sb:\u002F\u002F\u003Cnamespace>.servicebus.windows.net\u002F;SharedAccessKeyName=...\nEVENT_HUBS_NAME=\u003Cevent-hub-name>\nSTORAGE_CONNECTION_STRING=\u003Cfor-checkpointing>\n```\n\n## Best Practices\n\n1. **Use EventProcessorClient**: For production, provides load balancing and checkpointing\n2. **Batch Events**: Use `EventDataBatch` for efficient sending\n3. **Partition Keys**: Use for ordering guarantees within a partition\n4. **Checkpointing**: Checkpoint after processing to avoid reprocessing\n5. **Error Handling**: Handle transient errors with retries\n6. **Close Clients**: Always close producer\u002Fconsumer when done\n\n## Trigger Phrases\n\n- \"Event Hubs Java\"\n- \"event streaming Azure\"\n- \"real-time data ingestion\"\n- \"EventProcessorClient\"\n- \"event hub producer consumer\"\n- \"partition processing\"\n\n## When to Use\nThis skill is applicable to execute the workflow or actions described in the overview.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,215,297,"2026-05-16 13:06:20",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"DevOps","devops","mdi-cog-outline","CI\u002FCD、容器化、部署运维",3,162,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"a7e16815-27a9-49d6-86bf-f00918776021","1.0.0","azure-eventhub-java.zip",3115,"uploads\u002Fskills\u002Facfd24ee-2ce6-46e4-9677-77638ff19dfe\u002Fazure-eventhub-java.zip","6d021c859acc5494ddedd178995b6954f3beb17aacfa4e661d242add7612bba2","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":10803}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]