En este documento, se muestra cómo crear esquemas para los temas de Pub/Sub.
Antes de comenzar
Antes de crear un esquema, completa lo siguiente:
- Obtén información sobre los temas y el flujo de trabajo de publicación.
- Obtén información sobre cómo funcionan los esquemas de Pub/Sub.
- Crea un tema.
Funciones y permisos requeridos
Para obtener los permisos que necesitas para crear y administrar esquemas, pídele a tu administrador que te otorgue el rol de IAM de editor de Pub/Sub (roles/pubsub.editor
) en tu proyecto.
Para obtener más información sobre cómo otorgar roles, consulta Administra el acceso a proyectos, carpetas y organizaciones.
Este rol predefinido contiene los permisos necesarios para crear y administrar esquemas. Para ver los permisos exactos que son necesarios, expande la sección Permisos requeridos:
Permisos necesarios
Se requieren los siguientes permisos para crear y administrar esquemas:
-
Crea un esquema:
pubsub.schemas.create
-
Adjunta un esquema al tema:
pubsub.schemas.attach
-
Confirma una revisión de esquema:
pubsub.schemas.commit
-
Borra un esquema o una revisión de esquema:
pubsub.schemas.delete
-
Obtén un esquema o revisiones de esquema:
pubsub.schemas.get
-
Enumera los esquemas:
pubsub.schemas.list
-
Enumera las revisiones de esquema:
pubsub.schemas.listRevisions
-
Revierte un esquema:
pubsub.schemas.rollback
-
Valida un mensaje:
pubsub.schemas.validate
-
Obtén la política de IAM de un esquema:
pubsub.schemas.getIamPolicy
-
Configura la política de IAM para un esquema:
pubsub.schemas.setIamPolicy
También puedes obtener estos permisos con roles personalizados o con otros roles predefinidos.
Puedes otorgar roles y permisos a principales, como usuarios, grupos, dominios o cuentas de servicio. Puedes crear un esquema en un proyecto y vincularlo a un tema ubicado en un proyecto diferente. Asegúrate de tener los permisos necesarios para cada proyecto.
Crea un esquema
Puedes crear un esquema con la consola de Google Cloud, Google Cloud CLI, la API de Pub/Sub o las bibliotecas cliente de Cloud. Los siguientes son algunas pautas para crear un esquema:
Para que un esquema funcione con Pub/Sub, solo debes definir un tipo de nivel superior. Declaraciones de importación que hacen referencia a otros tipos no son compatibles.
Puedes asociar el mismo esquema a varios temas.
Puedes probar de forma manual si un mensaje se valida según un esquema.
Console
Para crear un esquema, sigue estos pasos:
En la consola de Google Cloud, ve a la página Esquemas de Pub/Sub.
Haz clic en Create schema (Crear esquema).
En el campo ID de esquema, ingresa un ID para tu esquema.
Si quieres conocer los lineamientos para asignar un nombre a un esquema, consulta Lineamientos para asignar un nombre a un tema, una suscripción o una instantánea.
En Tipo de esquema, selecciona Avro o búfer de protocolo.
Obtén más información sobre los tipos de esquema.
En el campo Definición de esquema, ingresa el búfer de protocolo o Avro. definición para tu esquema.
Por ejemplo, este es un esquema de muestra en Avro.
{ "type": "record", "name": "Avro", "fields": [ { "name": "ProductName", "type": "string", "default": "" }, { "name": "SKU", "type": "int", "default": 0 }, { "name": "InStock", "type": "boolean", "default": false } ] }
Opcional: Haz clic en Validar definición para verificar si la definición de esquema es correcta.
La verificación de validación no comprueba la compatibilidad del esquema con los mensajes que se publicarán. Mensajes de prueba en el siguiente paso.
Opcional: Puedes probar si se publican los mensajes con el esquema correcto.
Haz clic en Mensaje de prueba.
En la ventana Mensaje de prueba, selecciona un tipo de Codificación de mensajes.
En Cuerpo del mensaje, ingresa un mensaje de prueba.
Haga clic en Test.
Por ejemplo, este es un mensaje de muestra para el esquema de prueba. En este ejemplo, selecciona Codificación de mensajes como
JSON
.{"ProductName":"GreenOnions", "SKU":34543, "InStock":true}
Sal de la página del mensaje de prueba.
Haz clic en Crear para guardar el esquema.
gcloud
gcloud pubsub schemas create SCHEMA_ID \ --type=SCHEMA_TYPE \ --definition=SCHEMA_DEFINITION
Aquí:
- SCHEMA_TYPE es
avro
oprotocol-buffer
. - SCHEMA_DEFINITION es una
string
que contiene la definición del esquema, con el formato del tipo de esquema seleccionado.
También puedes especificar la definición de esquema en un archivo:
gcloud pubsub schemas create SCHEMA_ID \ --type=SCHEMA_TYPE \ --definition-file=SCHEMA_DEFINITION_FILE
Aquí:
- SCHEMA_TYPE es
avro
oprotocol-buffer
. - SCHEMA_DEFINITION_FILE es un
string
que contiene la ruta de acceso al archivo con la definición del esquema, con el formato que elijas tipo de esquema.
REST
Para crear un esquema, envía una solicitud POST como la siguiente:
POST https://pubsub.googleapis.com/v1/projects/PROJECT_ID/schemas/SCHEMA_ID Authorization: Bearer $(gcloud auth application-default print-access-token) Content-Type: application/json --data @response-body.json
Especifica los siguientes campos en el cuerpo de la solicitud:
{ "definition": SCHEMA_DEFINITION "type": SCHEMA_TYPE }
Aquí:
- SCHEMA_TYPE es
avro
oprotocol-buffer
. - SCHEMA_DEFINITION es una string que contiene la definición del esquema, con el formato correspondiente al tipo de esquema seleccionado.
El cuerpo de la respuesta debe contener una representación JSON de un recurso de esquema. Por ejemplo:
{ "name": SCHEMA_NAME, "type": SCHEMA_TYPE, "definition": SCHEMA_DEFINITION "revisionId": REVISION_ID "revisionCreateTime": REVISION_CREATE_TIME }
Aquí:
- REVISION_ID es el ID que generó el servidor para la revisión.
- REVISION_CREATE_TIME es la marca de tiempo ISO 8601 en la que se creó la revisión adicional.
C++
Antes de probar esta muestra, sigue las instrucciones de configuración de C++ en la guía de inicio rápido sobre el uso de bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Pub/Sub para C++.
Avro
Proto
C#
Antes de probar esta muestra, sigue las instrucciones de configuración de C# en la guía de inicio rápido sobre el uso de bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Pub/Sub para C#.
Avro
Proto
Go
Antes de probar esta muestra, sigue las instrucciones de configuración de Go en la guía de inicio rápido sobre el uso de bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Pub/Sub para Go.
Avro
Proto
Java
Antes de probar esta muestra, sigue las instrucciones de configuración de Java en la guía de inicio rápido sobre el uso de bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Pub/Sub para Java.
Avro
Proto
Node.js
Antes de probar esta muestra, sigue las instrucciones de configuración de Node.js en la guía de inicio rápido sobre el uso de bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Pub/Sub para Node.js.
Avro
Proto
Node.js
Antes de probar esta muestra, sigue las instrucciones de configuración de Node.js en la guía de inicio rápido sobre el uso de bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Pub/Sub para Node.js.
Avro
Proto
PHP
Antes de probar esta muestra, sigue las instrucciones de configuración de PHP en la guía de inicio rápido sobre el uso de bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Pub/Sub para PHP.
Avro
Proto
Python
Antes de probar esta muestra, sigue las instrucciones de configuración de Python en la guía de inicio rápido sobre el uso de bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Pub/Sub para Python.
Avro
Proto
Ruby
Antes de probar esta muestra, sigue las instrucciones de configuración de Ruby en la guía de inicio rápido sobre el uso de bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Pub/Sub para Ruby.
Avro
Proto
Después de crear un esquema, puedes ver los detalles del esquema en la página Esquemas.
Puedes asociar el esquema con un tema.