Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

Quickstart: Route custom events to an Azure function by using Event Grid

Feedback

In this article

Azure Event Grid is an event-routing service for the cloud. Azure Functions is one of thesupported event handlers.

In this quickstart, you use the Azure portal to create a custom topic, subscribe to the custom topic, and trigger the event to view the result. You send the events to an Azure function.

If you don't have an Azure account, create afree account before you begin.

Prerequisites

Create a function with an Event Grid trigger by using Visual Studio Code

In this section, you use Visual Studio Code to create a function with an Event Grid trigger.

Create a function

  1. Open Visual Studio Code.

  2. On the left bar, selectAzure.

  3. On the left pane, in theWORKSPACE section, selectAzure Functions on the command bar. Then selectCreate Function.

    Screenshot that shows the Azure tab of Visual Studio Code with the menu command for creating a function.

  4. Select a folder where you want to save the function code.

  5. For theCreate new project command, forLanguage, selectC#. SelectEnter.

    Screenshot that shows the selection of C Sharp as the language for developing an Azure function.

  6. For.NET runtime, select.NET 8.0 Isolated LTS, and then selectEnter.

  7. ForTemplate for the function, selectAzure Event Grid trigger. SelectEnter.

  8. ForFunction name, enter a name for your function. SelectEnter.

  9. ForNamespace, enter a name for the function's namespace. SelectEnter.

  10. Open the project in the current window or a new window, or add it to a workspace.

  11. Wait for the function to be created. The status of the function creation appears in the lower-right corner.

    Screenshot that shows the status of function creation.

  12. View the code in theYourFunctionName.cs file, specifically theRun method. It prints the information by using a logger.

    [Function(nameof(MyEventGridTriggerFunc))]public void Run([EventGridTrigger] CloudEvent cloudEvent){    _logger.LogInformation("Event type: {type}, Event subject: {subject}", cloudEvent.Type, cloudEvent.Subject);}

Deploy the function to Azure

  1. Select theAzure button on the left bar if theAzure pane isn't already open.

  2. Hover over your project and select theDeploy to Azure button.

    Screenshot that shows the button for deploying to Azure.

  3. In the dropdown list of the command palette, select+ Create new function app, and then selectEnter.

  4. ForName, enter a globally unique name for the new function app. SelectEnter.

  5. ForRuntime stack, select.NET 8 Isolated.

  6. ForLocation for your Azure resources, select a region that's close to you.

  7. The status of function app creation appears on theAZURE tab of the bottom pane. After the function app is created, you see the status of deploying the function that you created locally to the function app.

  8. After the deployment succeeds, expand theCreate Function App succeeded message. SelectClick to view resource. Confirm that your function is selected in theRESOURCES section on the left pane.

  9. Right-click your function, and then selectOpen in Portal.

    Screenshot that shows selections for opening a function in the portal.

  10. Sign in to Azure if necessary, and confirm that theFunction App page appears for your function.

  11. On the bottom pane, select your function.

    Screenshot that shows the selection of an Azure function on the Function App page.

  12. Switch to theLogs tab. Keep this tab open so that you can see logged messages when you send an event to an Event Grid topic later in this article.

    Screenshot that shows the Logs tab for a function in the Azure portal.

Create a custom topic

An Event Grid topic provides a user-defined endpoint that you post your events to.

  1. On a new tab of the web browser window, sign in to theAzure portal.

  2. On the search bar at the topic, search forEvent Grid Topics, and then selectEvent Grid Topics.

    Screenshot that shows the selection of Event Grid topics.

  3. On theTopics page, select+ Create on the command bar.

    Screenshot that shows the button for creating an Event Grid topic.

  4. On theCreate Topic pane, follow these steps:

    1. ForSubscription, select your Azure subscription.

    2. ForResource group, select the same resource group from the previous steps.

    3. ForName, provide a unique name for the custom topic. The topic name must be unique because a Domain Name System (DNS) entry represents it.

      Don't use the name shown in the example image. Instead, create your own name. It must be 3-50 characters and contain only the values a-z, A-Z, 0-9, and a hyphen (-).

    4. ForRegion, select a location for the Event Grid topic.

    5. SelectReview + create.

      Screenshot that shows the pane for creating a topic.

    6. On theReview + create tab, review settings and then selectCreate.

  5. After the custom topic is created, selectGo to resource to open theEvent Grid Topic page for that topic.

    Screenshot that shows the page for an Event Grid custom topic.

Subscribe to a custom topic

You subscribe to an Event Grid topic to tell Event Grid which events you want to track, and where to send the events.

  1. On theEvent Grid Topic page for your custom topic, select+ Event Subscription on the toolbar.

    Screenshot that shows the button for adding an event subscription on the toolbar.

  2. On theCreate Event Subscription pane, follow these steps:

    1. ForName, enter a name for the event subscription.

    2. ForEvent Schema, selectCloud Event Schema v1.0.

    3. ForEndpoint Type, selectAzure Function.

    4. SelectConfigure an endpoint.

      Screenshot that shows event subscription values.

  3. On theSelect Azure Function pane, follow these steps:

    1. ForSubscription, select the Azure subscription that has the function.

    2. ForResource group, select the resource group that has the function.

    3. ForFunction app, select your function app.

    4. ForFunction, select the function in the function app.

    5. SelectConfirm Selection.

      Screenshot that shows the pane for selecting a previously created Azure function.

  4. This step is optional, but we recommend it for production scenarios. On theCreate Event Subscription pane, go to theAdditional Features tab and set values forMax events per batch andPreferred batch size in kilobytes.

    Batching can give you high throughput. ForMax events per batch, set the maximum number of events that a subscription includes in a batch.Preferred batch size in kilobytes sets the preferred upper bound of batch size, but it can be exceeded if a single event is larger than this threshold.

    Screenshot that shows batching settings for an event subscription.

  5. On theCreate Event Subscription pane, selectCreate.

Send an event to your topic

Now, trigger an event to see how Event Grid distributes the message to your endpoint. Use either the Azure CLI or Azure PowerShell to send a test event to your custom topic. Typically, an application or an Azure service would send the event data.

The first example uses the Azure CLI. It gets the URL and key for the custom topic and sample event data. Use your custom topic name fortopicname. It creates sample event data.

Thedata element of the JSON is the payload of your event. Any well-formed JSON can go in this field. You can also use the subject field for advanced routing and filtering.

The cURL tool sends HTTP requests. In this article, you use cURL to send the event to the custom topic.

Azure CLI

  1. In the Azure portal, selectCloud Shell. If you're in Azure PowerShell mode, selectSwitch to Bash.

    Screenshot that shows the Bash window in Azure Cloud Shell.

  2. Set thetopicname andresourcegroupname variables that are used in the commands.

    ReplaceTOPICNAME with the name of your Event Grid topic.

    topicname="TOPICNAME"

    ReplaceRESOURCEGROUPNAME with the name of the Azure resource group that contains the Event Grid topic.

    resourcegroupname="RESOURCEGROUPNAME"
  3. Use the following command to get the endpoint for the topic. After you copy and paste the command, update the topic name and resource group name before you run it.

    endpoint=$(az eventgrid topic show --name $topicname -g $resourcegroupname --query "endpoint" --output tsv)
  4. Use the following command to get the key for the custom topic. After you copy and paste the command, update the topic name and resource group name before you run it.

    key=$(az eventgrid topic key list --name $topicname -g $resourcegroupname --query "key1" --output tsv)
  5. Copy the following statement with the event definition, and then selectEnter.

    event='[ {"id": "'"$RANDOM"'", "eventType": "recordInserted", "subject": "myapp/vehicles/motorcycles", "eventTime": "'`date +%Y-%m-%dT%H:%M:%S%z`'", "data":{ "make": "Ducati", "model": "Monster"},"dataVersion": "1.0"} ]'
  6. Run the following cURL command to post the event:

    curl -X POST -H "aeg-sas-key: $key" -d "$event" $endpoint
  7. Confirm that the message from the function appears on theLogs tab for your function in the Azure portal.

    Screenshot that shows the Logs tab for an Azure function.

Azure PowerShell

The second example uses Azure PowerShell to perform similar steps.

  1. In the Azure portal, selectCloud Shell or go to theAzure Cloud Shell page. In the upper-left corner of the Cloud Shell window, selectSwitch to PowerShell.

  2. Set the following variables. After you copy and paste each command, update the topic name and resource group name before you run it.

    $resourceGroupName = "RESOURCEGROUPNAME"
    $topicName = "TOPICNAME"
  3. Run the following commands to get the endpoint and the keys for the topic:

    $endpoint = (Get-AzEventGridTopic -ResourceGroupName $resourceGroupName -Name $topicName).Endpoint$keys = Get-AzEventGridTopicKey -ResourceGroupName $resourceGroupName -Name $topicName
  4. Prepare the event. Copy and run these statements in the Cloud Shell window:

    $eventID = Get-Random 99999#Date format should be SortableDateTimePattern (ISO 8601)$eventDate = Get-Date -Format s#Construct the body by using a hash table$htbody = @{    id= $eventID    eventType="recordInserted"    subject="myapp/vehicles/motorcycles"    eventTime= $eventDate       data= @{        make="Ducati"        model="Monster"    }    dataVersion="1.0"}#Use ConvertTo-Json to convert the event body from a hash table to a JSON object#Append square brackets to the converted JSON payload because they're expected in the event's JSON payload syntax$body = "["+(ConvertTo-Json $htbody)+"]"
  5. Use theInvoke-WebRequest cmdlet to send the event:

    Invoke-WebRequest -Uri $endpoint -Method POST -Body $body -Headers @{"aeg-sas-key" = $keys.Key1}
  6. Confirm that the message from the function appears on theLogs tab for your function in the Azure portal.

    Screenshot that shows the Logs tab for a function.

Verify that the function received the event

You triggered the event, and Event Grid sent the message to the endpoint that you configured when subscribing. Now you can check whether the function received it.

  1. Open theInvocation tab for your function.

    Screenshot that shows the Invocations tab of the Monitor page.

  2. To display the details, select the invocation.

    Screenshot that shows invocation details.

    You can also use theLogs tab.

    Screenshot that shows the Monitor view of a function with a log.

Clean up resources

If you plan to continue working with this event, don't clean up the resources that you created in this article. Otherwise, delete the resources that you created in this article.

  1. In the Azure portal search box, enterResource groups and then selectResource groups.

    Screenshot that shows the page for resource groups.

  2. Select the resource group to open the pane for its details.

  3. On the toolbar, selectDelete resource group.

  4. Confirm the deletion by entering the name of the resource group, and then selectDelete.

The Cloud Shell window created and used the other resource group that appears on theResource groups page. Delete this resource group if you don't plan to use the Cloud Shell window later.

Related content

Now that you know how to create topics and event subscriptions, learn more about what Event Grid can help you do:

To learn about publishing events to, and consuming events from, Event Grid by using various programming languages, see the following samples:


Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

  • Last updated on

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?