Introduction
In the current technology landscape, serverless computing has moved from a trendy buzzword to a powerful and effective way to develop and run applications that automatically scale to meet the demands of even the most complex, dynamic environments. Azure Event Grid and Azure Functions, both part of the Microsoft Azure platform, are two powerful technologies that can be used to build event-driven serverless applications.
This tutorial will cover the basics of serverless computing, introduce the architecture of Azure Event Grid and Azure Functions, and demonstrate how you can use these technologies together to build powerful event-driven serverless applications.
Understanding Serverless Computing
Serverless computing is an approach to building and running applications that eliminates the need for infrastructure management, server provisioning, and scale management. In a serverless computing environment, the cloud service provider manages the infrastructure (i.e., the servers, storage, and networking resources) for the application, leaving the developer to focus solely on writing application code.
Serverless computing is often used to build event-driven, serverless applications. These applications are designed to respond to specific events, such as a user uploading a file or a database record being created. Rather than running continuously, these applications are triggered by events, run a specific piece of code or function, and then return a response to the event that triggered it.
Azure Event Grid
Azure Event Grid is a fully managed event-routing service that allows you to build event-driven applications. It provides a simple yet powerful way to react to events from many different sources, including Azure services, third-party services, and custom applications.
Event Grid is built around the concept of a topic, which represents a logical grouping of events. Event sources push events to topics, which are then routed to event handlers. Event handlers can be anything from simple HTTP endpoints to complex Azure Functions.
Azure Functions
Azure Functions is a serverless compute service that allows you to run code in response to events. Functions can be written in C#, Java, PowerShell, JavaScript, and other languages and run on-demand without requiring you to manage any infrastructure.
Functions can be triggered by many different sources, including HTTP requests, Azure Event Grid events, Cron-like schedules, and more. When a function is triggered, it runs the specific code logic associated with the trigger and then returns a response.
Building an Event-Driven Serverless Application with Azure Event Grid and Functions
Now that we understand the basics of serverless computing and the architecture of Azure Event Grid and Functions, let’s build an event-driven serverless application that combines the two.
For demonstration purposes, we’ll build an application that receives a notification every time a new image is uploaded to an Azure Storage account. The notification will be sent to an Azure Function which will then resize the image and store it in a specified container.
Prerequisites
To follow along with this tutorial, you’ll need:
- An Azure subscription
- Azure Storage account
- Visual Studio Code (or your preferred IDE)
- Azure Functions CLI
Setting Up the Azure Storage Account and Azure Function
First, let’s create an Azure Storage account to store our images. Follow these steps:
- Log in to the Azure Portal.
- Click on “Create a resource” in the upper-left corner.
- Select “Storage account” from the “Storage” category.
- Fill in the required information for the storage account (e.g., name, resource group, location, and performance tier).
- Click “Create” to create the storage account.
Next, we’ll create the Azure Function that will resize the uploaded images. Follow these steps:
- Create a new directory for your function in your preferred location.
- Open your terminal or command prompt and navigate to the directory you just created.
- Run the following command to create a new C#-based Azure Function:
func new --name image-resizer --template "HttpTrigger"
- Run the following command to install the required packages and tools:
dotnet add package Microsoft.Azure.Storage.Blob
dotnet add package System.Drawing.Common
dotnet add package Microsoft.Extensions.Logging.Console
Adding Azure Event Grid Trigger to the Azure Function
Now that we have our Azure Function set up, we need to add an Azure Event Grid trigger to it so that it will be triggered every time a new image is uploaded to our Azure Storage account.
- In your terminal or command prompt, navigate to the directory where you created your Azure Function.
- Run the following command to add the Azure Event Grid trigger:
func extensions install --package Microsoft.Azure.WebJobs.Extensions.EventGrid --version 2.0.0-beta.1
- Open your
function.json
file and add the following to the “bindings” section:
{
"name": "eventGridEvent",
"type": "eventGridTrigger",
"direction": "in"
}
- Save the
function.json
file and add the following code to yourrun.csx
file:
#r "System.Drawing.Common"
using System.IO;
using System.Drawing;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Extensions.Storage;
using Microsoft.Extensions.Primitives;
public static async Task Run(EventGridEvent eventGridEvent, ILogger log, [Blob("{data.url}", FileAccess.Read)] Stream imageStream, [Blob("{data.url}-resized", FileAccess.Write)] Stream resizedImageStream)
{
log.LogInformation($"Received event: {eventGridEvent}");
var widthHeaderValue = eventGridEvent.Data["width"];
var heightHeaderValue = eventGridEvent.Data["height"];
int.TryParse(widthHeaderValue, out var width);
int.TryParse(heightHeaderValue, out var height);
using (var image = Image.FromStream(imageStream))
{
using (var resizedImage = new Bitmap(width, height))
{
using (var graphics = Graphics.FromImage(resizedImage))
{
graphics.DrawImage(image, 0, 0, width, height);
resizedImage.Save(resizedImageStream, image.RawFormat);
}
}
}
log.LogInformation($"Resized image and stored in 'resized' container");
}
Setting Up the Event Grid Subscription
Now that we have our Azure Function set up with an Event Grid trigger, we need to create a subscription to listen for new images uploaded to our Azure Storage account.
- Log in to the Azure Portal.
- Open your storage account.
- Click on “Events” in the left-hand menu.
- Click on “Add Event Subscription”.
- Fill in the required information for the subscription:
- Name: choose a name for the subscription
- Events: choose “Blob created” as the event type
- Endpoint type: choose “Azure Function”
- Endpoint: choose the name of the function you just created
- Select “Blob created” as the “Event schema”
- Set the “Subject begins with” field to
"/blobServices/default/containers/{containerName}/blobs/"
- Select the appropriate container for your images
- Click “Create” to create the subscription.
Testing the Application
Now that everything is set up, it’s time to test our application.
- Upload an image to the container specified in the
function.json
file. - Check the logs in the Azure portal to ensure the function was triggered and resized the image.
- Check the “resized” container in the Azure Storage account to ensure the resized image was created and uploaded successfully.
Conclusion
In this tutorial, we covered the basics of serverless computing, introduced the architecture of Azure Event Grid and Azure Functions, and demonstrated how to use these technologies together to build an event-driven serverless application. Serverless computing has introduced a new way of building and deploying applications that require minimal infrastructure management and are highly scalable. Azure Event Grid and Azure Functions provide a powerful combination of tools to help developers build these serverless applications with ease.