Crea un tema con la transferencia de Azure Event Hubs

Crea un tema con la transferencia de Azure Event Hubs

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

C++

Antes de probar esta muestra, sigue las instrucciones de configuración de C++ que encontrarás en la guía de inicio rápido de Pub/Sub con bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de C++ de Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para 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";
}

Go

Antes de probar esta muestra, sigue las instrucciones de configuración de Go que encontrarás en la guía de inicio rápido de Pub/Sub con bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Go de Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para 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 esta muestra, sigue las instrucciones de configuración de Java que encontrarás en la guía de inicio rápido de Pub/Sub con bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Java de Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para 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

/**
 * 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

/**
 * 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.`
  );
}

Python

Antes de probar esta muestra, sigue las instrucciones de configuración de Python que encontrarás en la guía de inicio rápido de Pub/Sub con bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Python de Pub/Sub.

Para autenticarte en Pub/Sub, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para 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")

¿Qué sigue?

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