Usare Java per inviare o ricevere eventi da Hub eventi di Azure (azure-messaging-eventhubs)Use Java to send events to or receive events from Azure Event Hubs (azure-messaging-eventhubs)
Questa guida di avvio rapido illustra come inviare e ricevere eventi da un hub eventi con il pacchetto Java azure-messaging-eventhubs.This quickstart shows how to send events to and receive events from an event hub using the azure-messaging-eventhubs Java package.
Importante
In questo argomento di avvio rapido viene usato il nuovo pacchetto azure-messaging-eventhubs.This quickstart uses the new azure-messaging-eventhubs package. Per una guida di avvio rapido sui pacchetti azure-eventhubs e azure-eventhubs-eph precedenti, vedere Inviare e ricevere eventi con azure-eventhubs e azure-eventhubs-eph.For a quickstart that uses the old azure-eventhubs and azure-eventhubs-eph packages, see Send and receive events using azure-eventhubs and azure-eventhubs-eph.
PrerequisitiPrerequisites
Se non si ha familiarità con Hub eventi di Azure, vedere Panoramica di Hub eventi prima di procedere con questa guida di avvio rapido.If you're new to Azure Event Hubs, see Event Hubs overview before you do this quickstart.
Per completare questa guida introduttiva è necessario soddisfare i prerequisiti seguenti:To complete this quickstart, you need the following prerequisites:
- Sottoscrizione di Microsoft Azure.Microsoft Azure subscription. Per usare i servizi di Azure, tra cui Hub eventi di Azure, è necessaria una sottoscrizione.To use Azure services, including Azure Event Hubs, you need a subscription. Se non si ha un account Azure, è possibile iscriversi per ottenere una versione di valutazione gratuita oppure usare i vantaggi della sottoscrizione di MSDN per la creazione di un account.If you don't have an existing Azure account, you can sign up for a free trial or use your MSDN subscriber benefits when you create an account.
- Ambiente di sviluppo in Java.A Java development environment. In questa guida di avvio rapido si usa Eclipse.This quickstart uses Eclipse. È necessario Java Development Kit (JDK) versione 8 o successiva.Java Development Kit (JDK) with version 8 or above is required.
- Creare uno spazio dei nomi di Hub eventi e un hub eventi.Create an Event Hubs namespace and an event hub. Il primo passaggio consiste nell'usare il portale di Azure per creare uno spazio dei nomi di tipo Hub eventi e ottenere le credenziali di gestione necessarie all'applicazione per comunicare con l'hub eventi.The first step is to use the Azure portal to create a namespace of type Event Hubs, and obtain the management credentials your application needs to communicate with the event hub. Per creare uno spazio dei nomi e un hub eventi, seguire la procedura descritta in questo articolo.To create a namespace and an event hub, follow the procedure in this article. Ottenere quindi la stringa di connessione allo spazio dei nomi di Hub eventi seguendo le istruzioni disponibili nell'articolo Ottenere una stringa di connessione.Then, get the connection string for the Event Hubs namespace by following instructions from the article: Get connection string. La stringa di connessione sarà necessaria più avanti in questa guida di avvio rapido.You use the connection string later in this quickstart.
Inviare eventiSend events
Questa sezione illustra come creare un'applicazione Java per inviare eventi a un hub eventi.This section shows you how to create a Java application to send events an event hub.
Aggiungere il riferimento alla libreria di Hub eventi di AzureAdd reference to Azure Event Hubs library
La libreria client Java per Hub eventi è disponibile nel repository centrale di Maven.The Java client library for Event Hubs is available in the Maven Central Repository. Per fare riferimento a questa libreria è possibile usare questa dichiarazione di dipendenza all'interno del file di progetto di Maven:You can reference this library using the following dependency declaration inside your Maven project file:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventhubs</artifactId>
<version>5.6.0</version>
</dependency>
Nota
Aggiornare la versione alla versione più recente pubblicata nel repository maven.Update the version to the latest version published to the Maven repository.
Scrivere codice per inviare messaggi all'hub eventiWrite code to send messages to the event hub
Per l'esempio seguente, creare prima un nuovo progetto Maven per un'applicazione console/shell nell'ambiente di sviluppo Java preferito.For the following sample, first create a new Maven project for a console/shell application in your favorite Java development environment. Aggiungere una classe denominata Sender
e includere il codice seguente nella classe:Add a class named Sender
, and add the following code to the class:
Importante
Aggiornare <Event Hubs namespace connection string>
con la stringa di connessione allo spazio dei nomi di hub eventi.Update <Event Hubs namespace connection string>
with the connection string to your Event Hubs namespace. Aggiornare <Event hub name>
con il nome dell'hub eventi nello spazio dei nomi.Update <Event hub name>
with the name of your event hub in the namespace.
import com.azure.messaging.eventhubs.*;
import java.util.Arrays;
import java.util.List;
public class Sender {
private static final String connectionString = "<Event Hubs namespace connection string>";
private static final String eventHubName = "<Event hub name>";
public static void main(String[] args) {
publishEvents();
}
}
Aggiungere il codice per pubblicare gli eventi nell'hub eventiAdd code to publish events to the event hub
Aggiungere un metodo denominato publishEvents
alla Sender
classe, come illustrato di seguito.Add a method named publishEvents
to the Sender
class as shown below.
/**
* Code sample for publishing events.
* @throws IllegalArgumentException if the event data is bigger than max batch size.
*/
public static void publishEvents() {
// create a producer client
EventHubProducerClient producer = new EventHubClientBuilder()
.connectionString(connectionString, eventHubName)
.buildProducerClient();
// sample events in an array
List<EventData> allEvents = Arrays.asList(new EventData("Foo"), new EventData("Bar"));
// create a batch
EventDataBatch eventDataBatch = producer.createBatch();
for (EventData eventData : allEvents) {
// try to add the event from the array to the batch
if (!eventDataBatch.tryAdd(eventData)) {
// if the batch is full, send it and then create a new batch
producer.send(eventDataBatch);
eventDataBatch = producer.createBatch();
// Try to add that event that couldn't fit before.
if (!eventDataBatch.tryAdd(eventData)) {
throw new IllegalArgumentException("Event is too large for an empty batch. Max size: "
+ eventDataBatch.getMaxSizeInBytes());
}
}
}
// send the last batch of remaining events
if (eventDataBatch.getCount() > 0) {
producer.send(eventDataBatch);
}
producer.close();
}
Compilare il programma e assicurarsi che non siano presenti errori.Build the program, and ensure that there are no errors. Questo programma verrà eseguito dopo l'esecuzione del programma ricevente.You'll run this program after you run the receiver program.
Ricevere eventiReceive events
Il codice di questa esercitazione si basa sull'esempio di codice EventProcessorSample in GitHub, che è possibile esaminare per vedere l'applicazione completa in funzione.The code in this tutorial is based on the EventProcessorClient sample on GitHub, which you can examine to see the full working application.
Avviso
Se si esegue questo codice nell'hub di Azure Stack, si verificheranno errori di runtime a meno che non si scelga una versione specifica dell'API di archiviazione come destinazione.If you run this code on Azure Stack Hub, you will experience runtime errors unless you target a specific Storage API version. Il motivo è che Event Hubs SDK usa l'ultima versione disponibile in Azure dell'API di archiviazione di Azure, che potrebbe non essere presente nella piattaforma dell'hub di Azure Stack.That's because the Event Hubs SDK uses the latest available Azure Storage API available in Azure that may not be available on your Azure Stack Hub platform. L'hub di Azure Stack potrebbe supportare una versione di Storage Blob SDK diversa da quelle solitamente disponibili in Azure.Azure Stack Hub may support a different version of Storage Blob SDK than those typically available on Azure. Se si usa Archiviazione BLOB di Azure come archivio di checkpoint, verificare la versione dell'API di archiviazione di Azure supportata per la build dell'hub di Azure Stack e scegliere tale versione come destinazione nel codice.If you are using Azure Blog Storage as a checkpoint store, check the supported Azure Storage API version for your Azure Stack Hub build and target that version in your code.
Se ad esempio l'esecuzione avviene nell'hub di Azure Stack versione 2005, la versione più recente disponibile per il servizio di archiviazione è 2019-02-02.For example, If you are running on Azure Stack Hub version 2005, the highest available version for the Storage service is version 2019-02-02. Per impostazione predefinita, la libreria client di Event Hubs SDK usa la versione più recente disponibile in Azure (2019-07-07 al momento del rilascio dell'SDK).By default, the Event Hubs SDK client library uses the highest available version on Azure (2019-07-07 at the time of the release of the SDK). In questo caso, oltre ai passaggi descritti in questa sezione, sarà anche necessario aggiungere codice destinato alla versione 2019-02-02 dell'API del servizio di archiviazione.In this case, besides following steps in this section, you will also need to add code to target the Storage service API version 2019-02-02. Per informazioni su come definire come destinazione una versione specifica dell'API di archiviazione, vedere questo esempio in GitHub.For an example on how to target a specific Storage API version, see this sample on GitHub.
Creare un account di archiviazione di Azure e un contenitore BLOBCreate an Azure Storage and a blob container
In questa guida di avvio rapido verrà usata una risorsa di archiviazione di Azure (nello specifico, l'archiviazione BLOB) come archivio di checkpoint.In this quickstart, you use Azure Storage (specifically, Blob Storage) as the checkpoint store. Il checkpoint è un processo mediante il quale un processore di eventi contrassegna o conferma la posizione dell'ultimo evento elaborato correttamente all'interno di una partizione.Checkpointing is a process by which an event processor marks or commits the position of the last successfully processed event within a partition. Il contrassegno di un checkpoint viene in genere eseguito all'interno della funzione che elabora gli eventi.Marking a checkpoint is typically done within the function that processes the events. Per altre informazioni sul checkpoint, vedere Processore di eventi.To learn more about checkpointing, see Event processor.
Seguire questa procedura per creare un account di archiviazione di Azure.Follow these steps to create an Azure Storage account.
Creare un account di archiviazione di AzureCreate an Azure Storage account
-
Prendere nota della stringa di connessione e del nome del contenitore.Note down the connection string and the container name. Questi valori verranno usati nel codice di ricezione.You'll use them in the receive code.
Aggiungere le librerie di Hub eventi al progetto JavaAdd Event Hubs libraries to your Java project
Aggiungere le dipendenze seguenti nel file pom.xml.Add the following dependencies in the pom.xml file.
- azure-messaging-eventhubsazure-messaging-eventhubs
- azure-messaging-eventhubs-checkpointstore-blobazure-messaging-eventhubs-checkpointstore-blob
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventhubs</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventhubs-checkpointstore-blob</artifactId>
<version>1.5.1</version>
</dependency>
</dependencies>
Aggiungere le istruzioni import seguenti all'inizio del file Java.Add the following import statements at the top of the Java file.
import com.azure.messaging.eventhubs.EventHubClientBuilder; import com.azure.messaging.eventhubs.EventProcessorClient; import com.azure.messaging.eventhubs.EventProcessorClientBuilder; import com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore; import com.azure.messaging.eventhubs.models.ErrorContext; import com.azure.messaging.eventhubs.models.EventContext; import com.azure.storage.blob.BlobContainerAsyncClient; import com.azure.storage.blob.BlobContainerClientBuilder; import java.util.function.Consumer;
Creare una classe denominata
Receiver
e aggiungere le variabili di stringa seguenti alla classe.Create a class namedReceiver
, and add the following string variables to the class. Sostituire i segnaposto con i valori corretti.Replace the placeholders with the correct values.Importante
Sostituire i segnaposto con i valori corretti.Replace the placeholders with the correct values.
<Event Hubs namespace connection string>
con la stringa di connessione allo spazio dei nomi di hub eventi.<Event Hubs namespace connection string>
with the connection string to your Event Hubs namespace. AggiornamentoUpdate<Event hub name>
con il nome dell'hub eventi nello spazio dei nomi.<Event hub name>
with the name of your event hub in the namespace.<Storage connection string>
con la stringa di connessione all'account di archiviazione di Azure.<Storage connection string>
with the connection string to your Azure storage account.<Storage container name>
con il nome del contenitore nell'archivio BLOB di Azure.<Storage container name>
with the name of your container in your Azure blob storage.
private static final String connectionString = "<Event Hubs namespace connection string>"; private static final String eventHubName = "<Event hub name>"; private static final String storageConnectionString = "<Storage connection string>"; private static final String storageContainerName = "<Storage container name>";
Aggiungere il metodo
main
seguente alla classe.Add the followingmain
method to the class.public static void main(String[] args) throws Exception { // Create a blob container client that you use later to build an event processor client to receive and process events BlobContainerAsyncClient blobContainerAsyncClient = new BlobContainerClientBuilder() .connectionString(storageConnectionString) .containerName(storageContainerName) .buildAsyncClient(); // Create a builder object that you will use later to build an event processor client to receive and process events and errors. EventProcessorClientBuilder eventProcessorClientBuilder = new EventProcessorClientBuilder() .connectionString(connectionString, eventHubName) .consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME) .processEvent(PARTITION_PROCESSOR) .processError(ERROR_HANDLER) .checkpointStore(new BlobCheckpointStore(blobContainerAsyncClient)); // Use the builder object to create an event processor client EventProcessorClient eventProcessorClient = eventProcessorClientBuilder.buildEventProcessorClient(); System.out.println("Starting event processor"); eventProcessorClient.start(); System.out.println("Press enter to stop."); System.in.read(); System.out.println("Stopping event processor"); eventProcessorClient.stop(); System.out.println("Event processor stopped."); System.out.println("Exiting process"); }
Aggiungere i due metodi helper (
PARTITION_PROCESSOR
eERROR_HANDLER
) che elaborano gli eventi e gli errori alla classeReceiver
.Add the two helper methods (PARTITION_PROCESSOR
andERROR_HANDLER
) that process events and errors to theReceiver
class.public static final Consumer<EventContext> PARTITION_PROCESSOR = eventContext -> { System.out.printf("Processing event from partition %s with sequence number %d with body: %s %n", eventContext.getPartitionContext().getPartitionId(), eventContext.getEventData().getSequenceNumber(), eventContext.getEventData().getBodyAsString()); if (eventContext.getEventData().getSequenceNumber() % 10 == 0) { eventContext.updateCheckpoint(); } }; public static final Consumer<ErrorContext> ERROR_HANDLER = errorContext -> { System.out.printf("Error occurred in partition processor for partition %s, %s.%n", errorContext.getPartitionContext().getPartitionId(), errorContext.getThrowable()); };
Compilare il programma e assicurarsi che non siano presenti errori.Build the program, and ensure that there are no errors.
Eseguire le applicazioniRun the applications
Eseguire prima l'applicazione ricevente.Run the receiver application first.
Quindi, eseguire l'applicazione mittente.Then, run the sender application.
Nella finestra dell'applicazione ricevente verificare che siano visualizzati gli eventi pubblicati dall'applicazione mittente.In the receiver application window, confirm that you see the events that were published by the sender application.
Starting event processor Press enter to stop. Processing event from partition 0 with sequence number 331 with body: Foo Processing event from partition 0 with sequence number 332 with body: Bar
Premere INVIO nella finestra dell'applicazione ricevente per arrestare l'applicazione.Press ENTER in the receiver application window to stop the application.
Starting event processor Press enter to stop. Processing event from partition 0 with sequence number 331 with body: Foo Processing event from partition 0 with sequence number 332 with body: Bar Stopping event processor Event processor stopped. Exiting process
Passaggi successiviNext steps
Vedere gli esempi seguenti in GitHub:See the following samples on GitHub: