Desencadenador de Azure Evento de Cuadrícula para Azure FunctionsAzure Evento Cuadrícula gatillo para Azure Funciones

Utilice la activación de la función de responder a un evento de la entrega a un tema de la lista de Eventos.

Para obtener información sobre los detalles de instalación y configuración, consulte la información general.For information on setup and configuration details, see the overview.

Para ver un ejemplo de un desencadenador HTTP, consulte Recepción de eventos en un punto de conexión HTTP.For an HTTP trigger example, see Receive events to an HTTP endpoint.

En el ejemplo siguiente se muestra una función de C# que se enlaza a EventGridEvent:The following example shows a C# function that binds to EventGridEvent:

Para más información, consulte Paquetes, Atributos, Configuración y Uso.For more information, see Packages, Attributes, Configuration, and Usage.

En el ejemplo siguiente se muestra una función de C# de Functions 1.x que enlaza a JObject:The following example shows a Functions 1.x C# function that binds to JObject:

En el ejemplo siguiente se muestra un enlace de desencadenador en un archivo function.json y una función de script de C# que usa el enlace.The following example shows a trigger binding in a function.json file and a C# script function that uses the binding.

Estos son los datos de enlace del archivo function.json:Here’s the binding data in the function.json file:

Este es un ejemplo que enlaza a EventGridEvent:Here’s an example that binds to EventGridEvent:

Para más información, consulte Paquetes, Atributos, Configuración y Uso.For more information, see Packages, Attributes, Configuration, and Usage.

Este es el código de script de C# de Functions 1.x que enlaza a JObject:Here’s Functions 1.x C# script code that binds to JObject:

En el ejemplo siguiente se muestra un enlace de desencadenador en un archivo function.json y una función de JavaScript que usa el enlace.The following example shows a trigger binding in a function.json file and a JavaScript function that uses the binding.

Estos son los datos de enlace del archivo function.json:Here’s the binding data in the function.json file:

Este es el código de JavaScript:Here’s the JavaScript code:

En el ejemplo siguiente se muestra un enlace de desencadenador en un archivo function.json y una función de Python que usa el enlace.The following example shows a trigger binding in a function.json file and a Python function that uses the binding.

Estos son los datos de enlace del archivo function.json:Here’s the binding data in the function.json file:

Este es el código de Python:Here’s the Python code:

En esta sección se incluyen los ejemplos siguientes:This section contains the following examples:

En los siguientes ejemplos, se muestra un enlace de desencadenador de Java que utiliza el enlace e imprime un evento. El evento se recibe primero como String y después como POJO.The following examples show trigger binding in Java that use the binding and print out an event, first receiving the event as String and second as a POJO.

En este ejemplo se usa el siguiente objeto POJO, que representa las propiedades de nivel superior de un evento de Event Grid:This example uses the following POJO, representing the top-level properties of an Event Grid event:

Al llegar, la carga útil JSON del evento se deserializa en el POJO EventSchema para que la función pueda usarla.Upon arrival, the event’s JSON payload is de-serialized into the EventSchema POJO for use by the function. Este proceso permite que la función obtenga acceso a las propiedades del evento de manera que esté orientada a los objetos.This process allows the function to access the event’s properties in an object-oriented way.

En la biblioteca en tiempo de ejecución de funciones de Java, utilice la anotación EventGridTrigger en los parámetros cuyo valor provendría de EventGrid.In the Java functions runtime library, use the EventGridTrigger annotation on parameters whose value would come from EventGrid. Los parámetros con estas anotaciones hacen que la función se ejecuta cuando llega un evento.Parameters with these annotations cause the function to run when an event arrives. Esta anotación se puede usar con tipos nativos de Java, POJO o valores que aceptan valores NULL mediante Optional.This annotation can be used with native Java types, POJOs, or nullable values using Optional.

En las bibliotecas de clases de C#, use el atributo EventGridTrigger.In C# class libraries, use the EventGridTrigger attribute.

A continuación, se muestra un atributo EventGridTrigger en una signatura de método:Here’s an EventGridTrigger attribute in a method signature:

Para un ejemplo completo, consulte el ejemplo de C#.For a complete example, see C# example.

Los atributos que no son compatibles con el guión de la C. de Los atributos que no son compatibles con el C-la Secuencia de comandos.

JavaScript no es compatible con los atributos. Los atributos que no son compatibles con el código JavaScript.

En Python no es compatible con los atributos. Los atributos que no son compatibles con el lenguaje de programación Python.

La anotación EventGridTrigger permite configurar mediante declaración un enlace de Event Grid con valores de configuración.The EventGridTrigger annotation allows you to declaratively configure an Event Grid binding by providing configuration values. Para más información, consulte las secciones Ejemplo y Configuración.See the example and configuration sections for more detail.

En la siguiente tabla se explican las propiedades de configuración de enlace que se establecen en el archivo function.json.The following table explains the binding configuration properties that you set in the function.json file. No hay parámetros de constructor ni propiedades que establecer en el atributo EventGridTrigger.There are no constructor parameters or properties to set in the EventGridTrigger attribute.

En Azure Functions 1.x, puede usar los tipos de parámetro siguientes para el desencadenador de Event Grid:In Azure Functions 1.x, you can use the following parameter types for the Event Grid trigger:

En Azure Functions 2.x y versiones posteriores, también tiene la opción de usar el tipo de parámetro siguiente para el desencadenador de Event Grid:In Azure Functions 2.x and higher, you also have the option to use the following parameter type for the Event Grid trigger:

Nota

En Functions v1, si intenta enlazar a Microsoft.Azure.WebJobs.Extensions.EventGrid.EventGridEvent, el compilador mostrará un mensaje «en desuso» y le avisará de que use en su lugar Microsoft.Azure.EventGrid.Models.EventGridEvent.In Functions v1 if you try to bind to Microsoft.Azure.WebJobs.Extensions.EventGrid.EventGridEvent, the compiler will display a «deprecated» message and advise you to use Microsoft.Azure.EventGrid.Models.EventGridEvent instead. Para usar el tipo más nuevo, haga referencia al paquete NuGet Microsoft.Azure.EventGrid y califique completamente el nombre del tipo EventGridEvent usando el prefijo Microsoft.Azure.EventGrid.Models.To use the newer type, reference the Microsoft.Azure.EventGrid NuGet package and fully qualify the EventGridEvent type name by prefixing it with Microsoft.Azure.EventGrid.Models.

En Azure Functions 1.x, puede usar los tipos de parámetro siguientes para el desencadenador de Event Grid:In Azure Functions 1.x, you can use the following parameter types for the Event Grid trigger:

En Azure Functions 2.x y versiones posteriores, también tiene la opción de usar el tipo de parámetro siguiente para el desencadenador de Event Grid:In Azure Functions 2.x and higher, you also have the option to use the following parameter type for the Event Grid trigger:

Nota

En Functions v1, si intenta enlazar a Microsoft.Azure.WebJobs.Extensions.EventGrid.EventGridEvent, el compilador mostrará un mensaje «en desuso» y le avisará de que use en su lugar Microsoft.Azure.EventGrid.Models.EventGridEvent.In Functions v1 if you try to bind to Microsoft.Azure.WebJobs.Extensions.EventGrid.EventGridEvent, the compiler will display a «deprecated» message and advise you to use Microsoft.Azure.EventGrid.Models.EventGridEvent instead. Para usar el tipo más nuevo, haga referencia al paquete NuGet Microsoft.Azure.EventGrid y califique completamente el nombre del tipo EventGridEvent usando el prefijo Microsoft.Azure.EventGrid.Models.To use the newer type, reference the Microsoft.Azure.EventGrid NuGet package and fully qualify the EventGridEvent type name by prefixing it with Microsoft.Azure.EventGrid.Models. Para información sobre cómo hacer referencia a paquetes NuGet en una función de script de C#, consulte Uso de paquetes NuGet.For information about how to reference NuGet packages in a C# script function, see Using NuGet packages

La instancia de Event Grid está disponible mediante el parámetro configurado en la propiedad name del archivo function.json.The Event Grid instance is available via the parameter configured in the function.json file’s name property.

La instancia de Event Grid está disponible mediante el parámetro configurado en la propiedad name del archivo function.json, con el tipo func.EventGridEvent.The Event Grid instance is available via the parameter configured in the function.json file’s name property, typed as func.EventGridEvent.

La instancia del evento de Event Grid está disponible mediante el parámetro asociado al atributo EventGridTrigger, con el tipo EventSchema.The Event Grid event instance is available via the parameter associated to the EventGridTrigger attribute, typed as an EventSchema. Consulte el ejemplo para más detalles.See the example for more detail.

Los datos para un evento de Event Grid se reciben como un objeto JSON en el cuerpo de una solicitud HTTP.Data for an Event Grid event is received as a JSON object in the body of an HTTP request. El código JSON es similar al del siguiente ejemplo:The JSON looks similar to the following example:

El ejemplo que se muestra es una matriz de un elemento.The example shown is an array of one element. Event Grid siempre envía una matriz y puede enviar más de un evento en la matriz.Event Grid always sends an array and may send more than one event in the array. El entorno en tiempo de ejecución invoca la función una vez para cada elemento de matriz.The runtime invokes your function once for each array element.

Las propiedades de nivel superior en los datos JSON del evento son las mismas entre todos los tipos de eventos, mientras que el contenido de la propiedad data es específico para cada tipo de evento.The top-level properties in the event JSON data are the same among all event types, while the contents of the data property are specific to each event type. El ejemplo mostrado es para un evento de almacenamiento de blobs.The example shown is for a blob storage event.

Para obtener una explicación de las propiedades comunes y específicas de eventos, consulte Propiedades de evento en la documentación de Event Grid.For explanations of the common and event-specific properties, see Event properties in the Event Grid documentation.

El tipo EventGridEvent define solo las propiedades de nivel superior; la propiedad Data es un JObject.The EventGridEvent type defines only the top-level properties; the Data property is a JObject.

Para empezar a recibir solicitudes HTTP de Event Grid, cree una suscripción a Event Grid que especifique la dirección URL de punto de conexión que invoca la función.To start receiving Event Grid HTTP requests, create an Event Grid subscription that specifies the endpoint URL that invokes the function.

Para las funciones que desarrolle en Azure Portal con el desencadenador de Event Grid, seleccione Agregar suscripción a Event Grid.For functions that you develop in the Azure portal with the Event Grid trigger, select Add Event Grid subscription.

Al seleccionar este vínculo, el portal abre la página Crear suscripción de eventos con la dirección URL del punto de conexión preinstalada.When you select this link, the portal opens the Create Event Subscription page with the endpoint URL prefilled.

Para obtener más información sobre cómo crear suscripciones mediante el Azure Portal, consulte Creación de eventos personalizados: Azure Portal en la documentación de Event Grid.For more information about how to create subscriptions by using the Azure portal, see Create custom event – Azure portal in the Event Grid documentation.

Para crear una suscripción mediante el uso de la CLI de Azure, utilice el comando az eventgrid event-subscription create.To create a subscription by using the Azure CLI, use the az eventgrid event-subscription create command.

El comando requiere la dirección URL del punto de conexión que invoca la función.The command requires the endpoint URL that invokes the function. En el siguiente ejemplo se muestra el patrón de la dirección URL específico de la versión:The following example shows the version-specific URL pattern:

La clave de sistema es una clave de autorización que debe incluirse en la dirección URL del punto de conexión para desencadenador de Event Grid.The system key is an authorization key that has to be included in the endpoint URL for an Event Grid trigger. En la siguiente sección se explica cómo obtener la clave del sistema.The following section explains how to get the system key.

En este ejemplo se suscribe a una cuenta de almacenamiento de blobs (con un marcador de posición para la clave del sistema):Here’s an example that subscribes to a blob storage account (with a placeholder for the system key):

Para más información sobre cómo crear una suscripción, consulte la guía de inicio rápido sobre el almacenamiento de blobs o cualquiera de las demás guías de inicio rápido de Event Grid.For more information about how to create a subscription, see the blob storage quickstart or the other Event Grid quickstarts.

Puede obtener la clave del sistema mediante la siguiente API (HTTP GET):You can get the system key by using the following API (HTTP GET):

Es una API de administración, por lo que requiere la clave maestra de la aplicación de función.This is an admin API, so it requires your function app master key. No confunda la clave del sistema (para invocar una función de desencadenador de Event Grid) con la clave maestra (para realizar tareas administrativas en la aplicación de función).Don’t confuse the system key (for invoking an Event Grid trigger function) with the master key (for performing administrative tasks on the function app). Cuando se suscriba a un tema de Event Grid, asegúrese de usar la clave del sistema.When you subscribe to an Event Grid topic, be sure to use the system key.

Este es un ejemplo de la respuesta que proporciona la clave del sistema:Here’s an example of the response that provides the system key:

Puede obtener la clave maestra de la aplicación de función en la pestaña Configuración de Function App del portal.You can get the master key for your function app from the Function app settings tab in the portal.

Importante

La clave maestra proporciona acceso de administrador a la aplicación de función.The master key provides administrator access to your function app. Esta clave no debe compartirse con terceros ni distribuirse en aplicaciones cliente nativas.Don’t share this key with third parties or distribute it in native client applications.

Para más información, consulte Claves de autorización en el artículo de referencia del desencadenador HTTP.For more information, see Authorization keys in the HTTP trigger reference article.

También puede enviar un HTTP PUT para especificar el mismo valor de la clave.Alternatively, you can send an HTTP PUT to specify the key value yourself.

Para probar localmente un desencadenador de Event Grid, debe enviar las solicitudes HTTP de Event Grid desde su origen en la nube a la máquina local.To test an Event Grid trigger locally, you have to get Event Grid HTTP requests delivered from their origin in the cloud to your local machine. Una manera de hacerlo es mediante la captura de solicitudes en línea y de reenviarlas manualmente a la máquina local:One way to do that is by capturing requests online and manually resending them on your local machine:

Cuando haya finalizado las pruebas, puede utilizar la misma suscripción para producción actualizando el punto de conexión.When you’re done testing, you can use the same subscription for production by updating the endpoint. Utilice el comando az eventgrid event-subscription update de la CLI de Azure.Use the az eventgrid event-subscription update Azure CLI command.

Para simplificar la captura de mensajes de evento, puede implementar una aplicación web de ejemplo que muestre los mensajes de los eventos.To simplify capturing event messages, you can deploy a pre-built web app that displays the event messages. La solución implementada incluye un plan de App Service, una aplicación web de App Service y el código fuente desde GitHub.The deployed solution includes an App Service plan, an App Service web app, and source code from GitHub.

Seleccione Deploy to Azure (Implementar en Azure) para implementar la solución en su suscripción.Select Deploy to Azure to deploy the solution to your subscription. En Azure Portal, proporcione valores para los parámetros.In the Azure portal, provide values for the parameters.

La implementación puede tardar unos minutos en completarse.The deployment may take a few minutes to complete. Después de que la implementación se haya realizado correctamente, puede ver la aplicación web para asegurarse de que se está ejecutando.After the deployment has succeeded, view your web app to make sure it’s running. En un explorador web, vaya a: https://.azurewebsites.netIn a web browser, navigate to: https://.azurewebsites.net

Verá el sitio, pero aún no se ha publicado en él ningún evento.You see the site but no events have been posted to it yet.

Cree una suscripción de Event Grid del tipo que desee probar y asígnele la dirección URL de su aplicación web como punto de conexión para la notificación de eventos.Create an Event Grid subscription of the type you want to test, and give it the URL from your web app as the endpoint for event notification. El punto de conexión de la aplicación web debe incluir el sufijo /api/updates/.The endpoint for your web app must include the suffix /api/updates/. Por lo tanto, dirección URL completa es https://.azurewebsites.net/api/updatesSo, the full URL is https://.azurewebsites.net/api/updates

Para obtener información sobre cómo crear suscripciones mediante Azure Portal, consulte Creación de eventos personalizados: Azure Portal en la documentación de Event Grid.For information about how to create subscriptions by using the Azure portal, see Create custom event – Azure portal in the Event Grid documentation.

Desencadene un evento que generará tráfico HTTP a su punto de conexión de aplicación web.Trigger an event that will generate HTTP traffic to your web app endpoint. Por ejemplo, si crea una suscripción de almacenamiento de blobs, cargue o elimine un blob.For example, if you created a blob storage subscription, upload or delete a blob. Cuando aparezca una solicitud en la aplicación web, copie el cuerpo de la solicitud.When a request shows up in your web app, copy the request body.

La solicitud de validación de la suscripción se recibirá primero; ignore cualquier solicitud de validación y copie la solicitud del evento.The subscription validation request will be received first; ignore any validation requests, and copy the event request.

Ejecute la función de Event Grid localmente.Run your Event Grid function locally.

Use una herramienta como Postman o curl para crear una solicitud HTTP POST:Use a tool such as Postman or curl to create an HTTP POST request:

Para 2.x y versiones posteriores, use el patrón siguiente:For 2.x and higher use the following pattern:

Para 1.x, use:Para uso de 1.x:

El parámetro functionName debe ser el nombre especificado en el atributo FunctionName.The functionName parameter must be the name specified in the FunctionName attribute.

Las capturas de pantalla siguientes muestran los encabezados y el cuerpo de la solicitud en Postman:The following screenshots show the headers and request body in Postman:

La función de desencadenador de Event Grid ejecuta y muestra registros similares a los del ejemplo siguiente:The Event Grid trigger function executes and shows logs similar to the following example:

Muchas gracias.

Cargando las opiniones de…

Muchas gracias.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *