|
| 1 | +--- |
| 2 | +title: Send or receive events from Azure Event Hubs using Java (latest) |
| 3 | +description: This article provides a walkthrough of creating a Java application that sends/receives events to/from Azure Event Hubs using the latest azure-messaging-eventhubs package. |
| 4 | +services: event-hubs |
| 5 | +author: spelluru |
| 6 | + |
| 7 | +ms.service: event-hubs |
| 8 | +ms.workload: core |
| 9 | +ms.topic: quickstart |
| 10 | +ms.date: 01/15/2020 |
| 11 | +ms.author: spelluru |
| 12 | + |
| 13 | +--- |
| 14 | + |
| 15 | +# Use Java to send events to or receive events from Azure Event Hubs (azure-messaging-eventhubs) |
| 16 | +This quickstart shows how to create Java applications to send events to or receive events from Azure Event Hubs. |
| 17 | + |
| 18 | +Azure Event Hubs is a Big Data streaming platform and event ingestion service, capable of receiving and processing millions of events per second. Event Hubs can process and store events, data, or telemetry produced by distributed software and devices. Data sent to an event hub can be transformed and stored using any real-time analytics provider or batching/storage adapters. For detailed overview of Event Hubs, see [Event Hubs overview](event-hubs-about.md) and [Event Hubs features](event-hubs-features.md). |
| 19 | + |
| 20 | +> [!IMPORTANT] |
| 21 | +> This quickstart uses the new **azure-messaging-eventhubs** package. For a quickstart that uses the old **azure-eventhubs** and **azure-eventhubs-eph** packages, see [this article](event-hubs-java-get-started-send.md). |
| 22 | +
|
| 23 | + |
| 24 | +## Prerequisites |
| 25 | + |
| 26 | +To complete this tutorial, you need the following prerequisites: |
| 27 | + |
| 28 | +- An active Azure account. If you do not have an Azure subscription, create a [free account](https://azure.microsoft.com/free/) before you begin. |
| 29 | +- A Java development environment. This tutorial uses [Eclipse](https://www.eclipse.org/). Java Development Kit (JDK) with version 8 or above is required. |
| 30 | +- **Create an Event Hubs namespace and an event hub**. The first step is to use the [Azure portal](https://portal.azure.com) to create a namespace of type Event Hubs, and obtain the management credentials your application needs to communicate with the event hub. To create a namespace and an event hub, follow the procedure in [this article](event-hubs-create.md). Then, get the value of access key for the event hub by following instructions from the article: [Get connection string](event-hubs-get-connection-string.md#get-connection-string-from-the-portal). You use the access key in the code you write later in this tutorial. The default key name is: **RootManageSharedAccessKey**. |
| 31 | + |
| 32 | +## Send events |
| 33 | +This section shows you how to create a Java application to send events an event hub. |
| 34 | + |
| 35 | +### Add reference to Azure Event Hubs library |
| 36 | + |
| 37 | +The Java client library for Event Hubs is available for use in Maven projects from the [Maven Central Repository](https://search.maven.org/search?q=a:azure-messaging-eventhubs). You can reference this library using the following dependency declaration inside your Maven project file: |
| 38 | + |
| 39 | +```xml |
| 40 | +<dependency> |
| 41 | + <groupId>com.azure</groupId> |
| 42 | + <artifactId>azure-messaging-eventhubs</artifactId> |
| 43 | + <version>5.0.1</version> |
| 44 | +</dependency> |
| 45 | +``` |
| 46 | + |
| 47 | +### Write code to send messages to the event hub |
| 48 | + |
| 49 | +For the following sample, first create a new Maven project for a console/shell application in your favorite Java development environment. Add a class named `SimpleSend`, and add the following code to the class: |
| 50 | + |
| 51 | +```java |
| 52 | +import com.azure.messaging.eventhubs.*; |
| 53 | +import static java.nio.charset.StandardCharsets.UTF_8; |
| 54 | + |
| 55 | +public class Sender { |
| 56 | + public static void main(String[] args) { |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +### Connection string and event hub |
| 62 | +This code uses the connection string to the Event Hubs namespace and the name of the event hub to build an Event Hubs client. |
| 63 | + |
| 64 | +```java |
| 65 | +String connectionString = "<CONNECTION STRING to EVENT HUBS NAMESPACE>"; |
| 66 | +String eventHubName = "<EVENT HUB NAME>"; |
| 67 | +``` |
| 68 | + |
| 69 | +### Create an Event Hubs Producer client |
| 70 | +This code creates a producer client object that's used to produce/send events to the event hub. |
| 71 | + |
| 72 | +```java |
| 73 | +EventHubProducerClient producer = new EventHubClientBuilder() |
| 74 | + .connectionString(connectionString, eventHubName) |
| 75 | + .buildProducer(); |
| 76 | +``` |
| 77 | + |
| 78 | +### Prepare a batch of events |
| 79 | +This code prepares a batch of events. |
| 80 | + |
| 81 | +```java |
| 82 | +EventDataBatch batch = producer.createBatch(); |
| 83 | +batch.tryAdd(new EventData("First event")); |
| 84 | +batch.tryAdd(new EventData("Second event")); |
| 85 | +batch.tryAdd(new EventData("Third event")); |
| 86 | +batch.tryAdd(new EventData("Fourth event")); |
| 87 | +batch.tryAdd(new EventData("Fifth event")); |
| 88 | +``` |
| 89 | + |
| 90 | +### Send the batch of events to the event hub |
| 91 | +This code sends the batch of events you prepared in the previous step to the event hub. The following code blocks on the send operation. |
| 92 | + |
| 93 | +```java |
| 94 | +producer.send(batch); |
| 95 | +``` |
| 96 | + |
| 97 | +### Close and cleanup |
| 98 | +This code closes the producer. |
| 99 | + |
| 100 | +```java |
| 101 | +producer.close(); |
| 102 | +``` |
| 103 | +### Complete code to send events |
| 104 | +Here is the complete code to send events to the event hub. |
| 105 | + |
| 106 | +```java |
| 107 | +import com.azure.messaging.eventhubs.*; |
| 108 | + |
| 109 | +public class Sender { |
| 110 | + public static void main(String[] args) { |
| 111 | + final String connectionString = "EVENT HUBS NAMESPACE CONNECTION STRING"; |
| 112 | + final String eventHubName = "EVENT HUB NAME"; |
| 113 | + |
| 114 | + // create a producer using the namespace connection string and event hub name |
| 115 | + EventHubProducerClient producer = new EventHubClientBuilder() |
| 116 | + .connectionString(connectionString, eventHubName) |
| 117 | + .buildProducer(); |
| 118 | + |
| 119 | + // prepare a batch of events to send to the event hub |
| 120 | + EventDataBatch batch = producer.createBatch(); |
| 121 | + batch.tryAdd(new EventData("First event")); |
| 122 | + batch.tryAdd(new EventData("Second event")); |
| 123 | + batch.tryAdd(new EventData("Third event")); |
| 124 | + batch.tryAdd(new EventData("Fourth event")); |
| 125 | + batch.tryAdd(new EventData("Fifth event")); |
| 126 | + |
| 127 | + // send the batch of events to the event hub |
| 128 | + producer.send(batch); |
| 129 | + |
| 130 | + // close the producer |
| 131 | + producer.close(); |
| 132 | + } |
| 133 | +} |
| 134 | +``` |
| 135 | + |
| 136 | +Build the program, and ensure that there are no errors. You will run this program after you run the receiver program. |
| 137 | + |
| 138 | +## Receive events |
| 139 | +The code in this tutorial is based on the [EventProcessorClient sample on GitHub](https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventProcessorClientSample.java), which you can examine to see the full working application. |
| 140 | + |
| 141 | +### Create a Java project |
| 142 | + |
| 143 | +The Java client library for Event Hubs is available for use in Maven projects from the [Maven Central Repository](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-eventhubs-eph%22), and can be referenced using the following dependency declaration inside your Maven project file: |
| 144 | + |
| 145 | +```xml |
| 146 | +<dependencies> |
| 147 | + <dependency> |
| 148 | + <groupId>com.azure</groupId> |
| 149 | + <artifactId>azure-messaging-eventhubs</artifactId> |
| 150 | + <version>5.0.1</version> |
| 151 | + </dependency> |
| 152 | +</dependencies> |
| 153 | +``` |
| 154 | + |
| 155 | +1. Use the following code to create a new class called `Receiver`. Replace the placeholders with the values used when you created the event hub and storage account: |
| 156 | + |
| 157 | + ```java |
| 158 | + import com.azure.messaging.eventhubs.*; |
| 159 | + import com.azure.messaging.eventhubs.models.ErrorContext; |
| 160 | + import com.azure.messaging.eventhubs.models.EventContext; |
| 161 | + import java.util.concurrent.TimeUnit; |
| 162 | + import java.util.function.Consumer; |
| 163 | + |
| 164 | + public class Receiver { |
| 165 | + |
| 166 | + private static final String connectionString = "EVENT HUBS NAMESPACE CONNECTION STRING"; |
| 167 | + private static final String eventHubName = "EVENT HUB NAME"; |
| 168 | + |
| 169 | + public static void main(String[] args) throws Exception { |
| 170 | + |
| 171 | + // function to process events |
| 172 | + Consumer<EventContext> processEvent = eventContext -> { |
| 173 | + System.out.print("Received event: "); |
| 174 | + // print the body of the event |
| 175 | + System.out.println(eventContext.getEventData().getBodyAsString()); |
| 176 | + eventContext.updateCheckpoint(); |
| 177 | + }; |
| 178 | + |
| 179 | + // function to process errors |
| 180 | + Consumer<ErrorContext> processError = errorContext -> { |
| 181 | + // print the error message |
| 182 | + System.out.println(errorContext.getThrowable().getMessage()); |
| 183 | + }; |
| 184 | + |
| 185 | + EventProcessorBuilder eventProcessorBuilder = new EventProcessorBuilder() |
| 186 | + .consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME) |
| 187 | + .connectionString(connectionString, eventHubName) |
| 188 | + .processEvent(processEvent) |
| 189 | + .processError(processError) |
| 190 | + .checkpointStore(new InMemoryCheckpointStore()); |
| 191 | + |
| 192 | + EventProcessorClient eventProcessorClient = eventProcessorClientBuilder.buildEventProcessorClient(); |
| 193 | + System.out.println("Starting event processor"); |
| 194 | + eventProcessorClient.start(); |
| 195 | + |
| 196 | + System.out.println("Press enter to stop."); |
| 197 | + System.in.read(); |
| 198 | + |
| 199 | + System.out.println("Stopping event processor"); |
| 200 | + eventProcessor.stop(); |
| 201 | + System.out.println("Event processor stopped."); |
| 202 | + |
| 203 | + System.out.println("Exiting process"); |
| 204 | + } |
| 205 | + } |
| 206 | + ``` |
| 207 | + |
| 208 | +2. Download the **InMemoryCheckpointStore.java** file from [GitHub](https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs), and add it to your project. |
| 209 | +3. Build the program, and ensure that there are no errors. |
| 210 | + |
| 211 | +## Run the applications |
| 212 | +1. Run the **receiver** application first. |
| 213 | +1. Then, run the **sender** application. |
| 214 | +1. In the **receiver** application window, confirm that you see the events that were published by the sender application. |
| 215 | +1. Press **ENTER** in the receiver application window to stop the application. |
| 216 | + |
| 217 | +## Next steps |
| 218 | +Check out [Java SDK samples on GitHub](https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs) |
| 219 | + |
0 commit comments