Crear un tema con la ingestión de Azure Event Hubs

Crear un tema con la ingestión de Azure Event Hubs

Investigar más

Para obtener documentación detallada que incluya este código de muestra, consulta lo siguiente:

Código de ejemplo

C++

Antes de probar este ejemplo, sigue las instrucciones de configuración de C++ que se indican en la guía de inicio rápido de Pub/Sub con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API C++ Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

namespace pubsub = ::google::cloud::pubsub;
namespace pubsub_admin = ::google::cloud::pubsub_admin;
[](pubsub_admin::TopicAdminClient client, std::string project_id,
   std::string topic_id, std::string const& resource_group,
   std::string const& event_hubs_namespace, std::string const& event_hub,
   std::string const& client_id, std::string const& tenant_id,
   std::string const& subscription_id,
   std::string const& gcp_service_account) {
  google::pubsub::v1::Topic request;
  request.set_name(
      pubsub::Topic(std::move(project_id), std::move(topic_id)).FullName());
  auto* azure_event_hubs = request.mutable_ingestion_data_source_settings()
                               ->mutable_azure_event_hubs();
  azure_event_hubs->set_resource_group(resource_group);
  azure_event_hubs->set_namespace_(event_hubs_namespace);
  azure_event_hubs->set_event_hub(event_hub);
  azure_event_hubs->set_client_id(client_id);
  azure_event_hubs->set_tenant_id(tenant_id);
  azure_event_hubs->set_subscription_id(subscription_id);
  azure_event_hubs->set_gcp_service_account(gcp_service_account);

  auto topic = client.CreateTopic(request);
  // Note that kAlreadyExists is a possible error when the library retries.
  if (topic.status().code() == google::cloud::StatusCode::kAlreadyExists) {
    std::cout << "The topic already exists\n";
    return;
  }
  if (!topic) throw std::move(topic).status();

  std::cout << "The topic was successfully created: " << topic->DebugString()
            << "\n";
}

C#

Antes de probar este ejemplo, sigue las instrucciones de configuración de C# que se indican en la guía de inicio rápido de Pub/Sub con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API C# Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.


using Google.Cloud.PubSub.V1;
using System;

public class CreateTopicWithAzureEventHubsIngestionSample
{
    public Topic CreateTopicWithAzureEventHubsIngestion(string projectId, string topicId, string resourceGroup, string nameSpace, string eventHub, string clientId, string tenantId, string subscriptionId, string gcpServiceAccount)
    {
        // Define settings for Azure Event Hubs ingestion
        IngestionDataSourceSettings ingestionDataSourceSettings = new IngestionDataSourceSettings
        {
            AzureEventHubs = new IngestionDataSourceSettings.Types.AzureEventHubs
            {
                ResourceGroup = resourceGroup,
                Namespace = nameSpace,
                EventHub = eventHub,
                ClientId = clientId,
                TenantId = tenantId,
                SubscriptionId = subscriptionId,
                GcpServiceAccount = gcpServiceAccount
            }
        };

        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        Topic topic = new Topic()
        {
            Name = TopicName.FormatProjectTopic(projectId, topicId),
            IngestionDataSourceSettings = ingestionDataSourceSettings
        };
        Topic createdTopic = publisher.CreateTopic(topic);
        Console.WriteLine($"Topic {topic.Name} created.");

        return createdTopic;
    }
}

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración de Go que se indican en la guía de inicio rápido de Pub/Sub con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Go Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
)

func createTopicWithAzureEventHubsIngestion(w io.Writer, projectID, topicID, resourceGroup, namespace, eventHub, clientID, tenantID, subID, gcpSA string) error {
	// projectID := "my-project-id"
	// topicID := "my-topic"

	// // Azure Event Hubs ingestion settings.
	// resourceGroup := "resource-group"
	// namespace := "namespace"
	// eventHub := "event-hub"
	// clientID := "client-id"
	// tenantID := "tenant-id"
	// subID := "subscription-id"
	// gcpSA := "gcp-service-account"

	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	cfg := &pubsub.TopicConfig{
		IngestionDataSourceSettings: &pubsub.IngestionDataSourceSettings{
			Source: &pubsub.IngestionDataSourceAzureEventHubs{
				ResourceGroup:     resourceGroup,
				Namespace:         namespace,
				EventHub:          eventHub,
				ClientID:          clientID,
				TenantID:          tenantID,
				SubscriptionID:    subID,
				GCPServiceAccount: gcpSA,
			},
		},
	}
	t, err := client.CreateTopicWithConfig(ctx, topicID, cfg)
	if err != nil {
		return fmt.Errorf("CreateTopic: %w", err)
	}
	fmt.Fprintf(w, "Created topic with azure event hubs ingestion: %v\n", t)
	return nil
}

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración de Java que se indican en la guía de inicio rápido de Pub/Sub con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Java Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.IngestionDataSourceSettings;
import com.google.pubsub.v1.Topic;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class CreateTopicWithAzureEventHubsIngestionExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";
    // Azure Event Hubs ingestion settings.
    String resourceGroup = "resource-group";
    String namespace = "namespace";
    String eventHub = "event-hub";
    String clientId = "client-id";
    String tenantId = "tenant-id";
    String subscriptionId = "subscription-id";
    String gcpServiceAccount = "gcp-service-account";

    createTopicWithAzureEventHubsIngestionExample(
        projectId,
        topicId,
        resourceGroup,
        namespace,
        eventHub,
        clientId,
        tenantId,
        subscriptionId,
        gcpServiceAccount);
  }

  public static void createTopicWithAzureEventHubsIngestionExample(
      String projectId,
      String topicId,
      String resourceGroup,
      String namespace,
      String eventHub,
      String clientId,
      String tenantId,
      String subscriptionId,
      String gcpServiceAccount)
      throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);

      IngestionDataSourceSettings.AzureEventHubs azureEventHubs =
          IngestionDataSourceSettings.AzureEventHubs.newBuilder()
              .setResourceGroup(resourceGroup)
              .setNamespace(namespace)
              .setEventHub(eventHub)
              .setClientId(clientId)
              .setTenantId(tenantId)
              .setSubscriptionId(subscriptionId)
              .setGcpServiceAccount(gcpServiceAccount)
              .build();
      IngestionDataSourceSettings ingestionDataSourceSettings =
          IngestionDataSourceSettings.newBuilder().setAzureEventHubs(azureEventHubs).build();

      Topic topic =
          topicAdminClient.createTopic(
              Topic.newBuilder()
                  .setName(topicName.toString())
                  .setIngestionDataSourceSettings(ingestionDataSourceSettings)
                  .build());

      System.out.println(
          "Created topic with Azure Event Hubs ingestion settings: " + topic.getAllFields());
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración de Node.js que se indican en la guía de inicio rápido de Pub/Sub con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Node.js Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const resourceGroup = 'YOUR_RESOURCE_GROUP';
// const namespace = 'YOUR_NAMESPACE';
// const eventHub = 'YOUR_EVENT_HUB';
// const clientId = 'YOUR_CLIENT_ID';
// const tenantId = 'YOUR_TENANT_ID';
// const subscriptionId = 'YOUR_SUBSCRIPTION_ID';
// const gcpServiceAccount = 'ingestion-account@...';

// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function createTopicWithAzureEventHubsIngestion(
  topicNameOrId,
  resourceGroup,
  namespace,
  eventHub,
  clientId,
  tenantId,
  subscriptionId,
  gcpServiceAccount,
) {
  // Creates a new topic with Azure Event Hubs ingestion.
  await pubSubClient.createTopic({
    name: topicNameOrId,
    ingestionDataSourceSettings: {
      azureEventHubs: {
        resourceGroup,
        namespace,
        eventHub,
        clientId,
        tenantId,
        subscriptionId,
        gcpServiceAccount,
      },
    },
  });
  console.log(
    `Topic ${topicNameOrId} created with Azure Event Hubs ingestion.`,
  );
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración de Node.js que se indican en la guía de inicio rápido de Pub/Sub con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Node.js de Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const resourceGroup = 'YOUR_RESOURCE_GROUP';
// const namespace = 'YOUR_NAMESPACE';
// const eventHub = 'YOUR_EVENT_HUB';
// const clientId = 'YOUR_CLIENT_ID';
// const tenantId = 'YOUR_TENANT_ID';
// const subscriptionId = 'YOUR_SUBSCRIPTION_ID';
// const gcpServiceAccount = 'ingestion-account@...';

// Imports the Google Cloud client library
import {PubSub} from '@google-cloud/pubsub';

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function createTopicWithAzureEventHubsIngestion(
  topicNameOrId: string,
  resourceGroup: string,
  namespace: string,
  eventHub: string,
  clientId: string,
  tenantId: string,
  subscriptionId: string,
  gcpServiceAccount: string,
) {
  // Creates a new topic with Azure Event Hubs ingestion.
  await pubSubClient.createTopic({
    name: topicNameOrId,
    ingestionDataSourceSettings: {
      azureEventHubs: {
        resourceGroup,
        namespace,
        eventHub,
        clientId,
        tenantId,
        subscriptionId,
        gcpServiceAccount,
      },
    },
  });
  console.log(
    `Topic ${topicNameOrId} created with Azure Event Hubs ingestion.`,
  );
}

PHP

Antes de probar este ejemplo, sigue las instrucciones de configuración de PHP que se indican en la guía de inicio rápido de Pub/Sub con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API PHP Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub topic with Azure Event Hubs ingestion.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 * @param string $resourceGroup  The name of the resource group within the azure subscription.
 * @param string $namespace  The name of the Event Hubs namespace.
 * @param string $eventHub  The name of the Event Hub.
 * @param string $clientId  The client id of the Azure application that is being used to authenticate Pub/Sub.
 * @param string $tenantId  The tenant id of the Azure application that is being used to authenticate Pub/Sub.
 * @param string $subscriptionId  The Azure subscription id.
 * @param string $gcpServiceAccount  The GCP service account to be used for Federated Identity authentication.
 */
function create_topic_with_azure_event_hubs_ingestion(
    string $projectId,
    string $topicName,
    string $resourceGroup,
    string $namespace,
    string $eventHub,
    string $clientId,
    string $tenantId,
    string $subscriptionId,
    string $gcpServiceAccount
): void {
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);

    $topic = $pubsub->createTopic($topicName, [
        'ingestionDataSourceSettings' => [
            'azure_event_hubs' => [
                'resource_group' => $resourceGroup,
                'namespace' => $namespace,
                'event_hub' => $eventHub,
                'client_id' => $clientId,
                'tenant_id' => $tenantId,
                'subscription_id' => $subscriptionId,
                'gcp_service_account' => $gcpServiceAccount
            ]
        ]
    ]);

    printf('Topic created: %s' . PHP_EOL, $topic->name());
}

Python

Antes de probar este ejemplo, sigue las instrucciones de configuración de Python que se indican en la guía de inicio rápido de Pub/Sub con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Python Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

from google.cloud import pubsub_v1
from google.pubsub_v1.types import Topic
from google.pubsub_v1.types import IngestionDataSourceSettings

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"
# resource_group = "your-resource-group"
# namespace = "your-namespace"
# event_hub = "your-event-hub"
# client_id = "your-client-id"
# tenant_id = "your-tenant-id"
# subscription_id = "your-subscription-id"
# gcp_service_account = "your-gcp-service-account"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)

request = Topic(
    name=topic_path,
    ingestion_data_source_settings=IngestionDataSourceSettings(
        azure_event_hubs=IngestionDataSourceSettings.AzureEventHubs(
            resource_group=resource_group,
            namespace=namespace,
            event_hub=event_hub,
            client_id=client_id,
            tenant_id=tenant_id,
            subscription_id=subscription_id,
            gcp_service_account=gcp_service_account,
        )
    ),
)

topic = publisher.create_topic(request=request)

print(f"Created topic: {topic.name} with Azure Event Hubs Ingestion Settings")

Ruby

Antes de probar este ejemplo, sigue las instrucciones de configuración de Ruby que se indican en la guía de inicio rápido de Pub/Sub con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Ruby Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

# topic_id = "your-topic-id"
# resource_group = "resource-group"
# namespace = "namespace"
# event_hub = "event-hub"
# client_id = "11111111-1111-1111-1111-11111111111"
# tenant_id = "22222222-2222-2222-2222-222222222222"
# subscription_id = "33333333-3333-3333-3333-333333333333"
# gcp_service_account = "service-account@project.iam.gserviceaccount.com"

pubsub = Google::Cloud::Pubsub.new
topic_admin = pubsub.topic_admin

topic = topic_admin.create_topic name: pubsub.topic_path(topic_id),
                                 ingestion_data_source_settings: {
                                   azure_event_hubs: {
                                     resource_group: resource_group,
                                     namespace: namespace,
                                     event_hub: event_hub,
                                     client_id: client_id,
                                     tenant_id: tenant_id,
                                     subscription_id: subscription_id,
                                     gcp_service_account: gcp_service_account
                                   }
                                 }

puts "Topic with Azure Event Hubs Ingestion #{topic.name} created."

Siguientes pasos

Para buscar y filtrar ejemplos de código de otros Google Cloud productos, consulta el Google Cloud navegador de ejemplos.