Search code examples
javaazureazure-eventhub

How to create azure event hub topic programmatically in java?


I want to know the code/class used to create azure eventhub topics in java.

I searched and found that we can create using .Net like below.

var manager = new Microsoft.ServiceBus.NamespaceManager("mynamespace.servicebus.windows.net");
var description = manager.CreateEventHub("MyEventHub");

I want the same for java..is it possible?


Solution

  • Per my experience, you need to do two steps to create a namespace and an entity for Azure Event Hubs in Java, as below.

    To create Namespaces:

    1. Using Azure SDK for Java to create an EventHub namespace.

      First, add the dependency in the pom.xml file of Maven project.

      <dependency>
          <groupId>com.microsoft.azure</groupId>
          <artifactId>azure</artifactId>
          <version>1.1.0</version>
      </dependency>
      

      Here is my sample code using application token credential.

      String clientId = "<your client id regiested on AAD>";
      String domain = "<your talnet id or domain name>";
      String secret = "<your client key>";
      String subscription = "<your subscription id>";
      AzureTokenCredentials cred = new ApplicationTokenCredentials(clientId, domain, secret, AzureEnvironment.AZURE);
      Azure azure = Azure.configure().authenticate(cred).withSubscription(subscription);
      
      String name = "<your eventhub namespace name>";
      String region = "<your eventhub region like 'East Asia'>";
      String resourceGroupName = "<your resource group name>";
      String resourceType = "namespaces";
      String providerNamespace = "Microsoft.EventHub";
      azure.genericResources().define(name).withRegion(region)
              .withExistingResourceGroup(resourceGroupName).withResourceType(resourceType)
              .withProviderNamespace(providerNamespace).withoutPlan()
              .create();
      
    2. To create an EventHub namespace via the REST API Create Or Update of Event Hubs Namespaces in Java.

    To create Entities:

    1. Via the REST API Create Or Update of Event Hubs in Java.
    2. Via the REST API Create Event Hub of Entity management REST in Java.
    3. Just create entity on Azure portal as the figure below. enter image description here

    Otherwise, you can try to follow the document Create an EventHubs namespace, Event Hub, and consumer group to create it via ARM template in Java with Azure SDK.

    azure.deployments().define("<deployment-name>").withExistingResourceGroup("<resource-group-name>").withTemplate("<template-uri>").withParameters("<parameters required in the template>").withMode(DeploymentMode.COMPLETE).create();
    

    Hope it helps.