Tutorial: Get started with Azure Functions triggers in Azure Cache for Redis
This tutorial shows how to implement basic triggers with Azure Cache for Redis and Azure Functions. It guides you through using Visual Studio Code (VS Code) to write and deploy an Azure function in C#.
In this tutorial, you learn how to:
- Set up the necessary tools.
- Configure and connect to a cache.
- Create an Azure function and deploy code to it.
- Confirm the logging of triggers.
Prerequisites
- An Azure subscription. If you don't have an Azure subscription, create a free account.
- Visual Studio Code.
Set up an Azure Cache for Redis instance
Create a new Azure Cache for Redis instance by using the Azure portal or your preferred CLI tool. This tutorial uses a Standard C1 instance, which is a good starting point. Use the quickstart guide to get started.
The default settings should suffice. This tutorial uses a public endpoint for demonstration, but we recommend that you use a private endpoint for anything in production.
Creating the cache can take a few minutes. You can move to the next section while the process finishes.
Set up Visual Studio Code
If you haven't installed the Azure Functions extension for VS Code, search for Azure Functions on the EXTENSIONS menu, and then select Install. If you don't have the C# extension installed, install it, too.
Go to the Azure tab. Sign in to your Azure account.
Create a new local folder on your computer to hold the project that you're building. This tutorial uses RedisAzureFunctionDemo as an example.
On the Azure tab, create a new function app by selecting the lightning bolt icon in the upper right of the Workspace tab.
Select Create function....
Select the folder that you created to start the creation of a new Azure Functions project. You get several on-screen prompts. Select:
- C# as the language.
- .NET 6.0 LTS as the .NET runtime.
- Skip for now as the project template.
If you don't have the .NET Core SDK installed, you're prompted to do so.
Confirm that the new project appears on the EXPLORER pane.
Install the necessary NuGet package
You need to install Microsoft.Azure.WebJobs.Extensions.Redis
, the NuGet package for the Redis extension that allows Redis keyspace notifications to be used as triggers in Azure Functions.
Install this package by going to the Terminal tab in VS Code and entering the following command:
dotnet add package Microsoft.Azure.WebJobs.Extensions.Redis --prerelease
Configure the cache
Go to your newly created Azure Cache for Redis instance.
Go to your cache in the Azure portal, and then:
On the resource menu, select Advanced settings.
Scroll down to the notify-keyspace-events box and enter KEA.
KEA is a configuration string that enables keyspace notifications for all keys and events. For more information on keyspace configuration strings, see the Redis documentation.
Select Save at the top of the window.
Select Access keys from the resource menu, and then write down or copy the contents of the Primary connection string box. This string is used to connect to the cache.
Set up the example code
Go back to VS Code and add a file called RedisFunctions.cs to the project.
Copy and paste the following code sample into the new file:
using Microsoft.Extensions.Logging; using StackExchange.Redis; namespace Microsoft.Azure.WebJobs.Extensions.Redis.Samples { public static class RedisSamples { public const string connectionString = "redisConnectionString"; [FunctionName(nameof(PubSubTrigger))] public static void PubSubTrigger( [RedisPubSubTrigger(connectionString, "pubsubTest")] string message, ILogger logger) { logger.LogInformation(message); } [FunctionName(nameof(KeyspaceTrigger))] public static void KeyspaceTrigger( [RedisPubSubTrigger(connectionString, "__keyspace@0__:keyspaceTest")] string message, ILogger logger) { logger.LogInformation(message); } [FunctionName(nameof(KeyeventTrigger))] public static void KeyeventTrigger( [RedisPubSubTrigger(connectionString, "__keyevent@0__:del")] string message, ILogger logger) { logger.LogInformation(message); } [FunctionName(nameof(ListTrigger))] public static void ListTrigger( [RedisListTrigger(connectionString, "listTest")] string entry, ILogger logger) { logger.LogInformation(entry); } [FunctionName(nameof(StreamTrigger))] public static void StreamTrigger( [RedisStreamTrigger(connectionString, "streamTest")] string entry, ILogger logger) { logger.LogInformation(entry); } } }
This tutorial shows multiple ways to trigger on Redis activity:
PubSubTrigger
, which is triggered when an activity is published to the Pub/Sub channel namedpubsubTest
.KeyspaceTrigger
, which is built on the Pub/Sub trigger. Use it to look for changes to thekeyspaceTest
key.KeyeventTrigger
, which is also built on the Pub/Sub trigger. Use it to look for any use of theDEL
command.ListTrigger
, which looks for changes to thelistTest
list.StreamTrigger
, which looks for changes to thestreamTest
stream.
Connect to your cache
To trigger on Redis activity, you need to pass in the connection string of your cache instance. This information is stored in the local.settings.json file that was automatically created in your folder. We recommend that you use the local settings file as a security best practice.
To connect to your cache, add a
ConnectionStrings
section in the local.settings.json file, and then add your connection string by using theredisConnectionString
parameter. The section should look like this example:{ "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "", "FUNCTIONS_WORKER_RUNTIME": "dotnet", "redisConnectionString": "<your-connection-string>" } }
The code in RedisConnection.cs looks to this value when it's running locally:
public const string connectionString = "redisConnectionString";
Important
This example is simplified for the tutorial. For production use, we recommend that you use Azure Key Vault to store connection string information.
Build and run the code locally
Switch to the Run and debug tab in VS Code and select the green arrow to debug the code locally. If you don't have Azure Functions core tools installed, you're prompted to do so. In that case, you'll need to restart VS Code after installing.
The code should build successfully. You can track its progress in the terminal output.
To test the trigger functionality, try creating and deleting the
keyspaceTest
key.You can use any way you prefer to connect to the cache. An easy way is to use the built-in console tool in the Azure Cache for Redis portal. Go to the cache instance in the Azure portal, and then select Console to open it.
After the console is open, try the following commands:
SET keyspaceTest 1
SET keyspaceTest 2
DEL keyspaceTest
PUBLISH pubsubTest testMessage
LPUSH listTest test
XADD streamTest * name Clippy
Confirm that the triggers are being activated in the terminal.
Deploy code to an Azure function
Create a new Azure function:
Go back to the Azure tab and expand your subscription.
Right-click Function App, and then select Create Function App in Azure (Advanced).
You get several prompts for information to configure the new function app:
- Enter a unique name.
- Select .NET 6 (LTS) as the runtime stack.
- Select either Linux or Windows (either works).
- Select an existing or new resource group to hold the function app.
- Select the same region as your cache instance.
- Select Premium as the hosting plan.
- Create a new Azure App Service plan.
- Select the EP1 pricing tier.
- Select an existing storage account or create a new one.
- Create a new Application Insights resource. You use the resource to confirm that the trigger is working.
Important
Redis triggers aren't currently supported on consumption functions.
Wait a few minutes for the new function app to be created. It appears under Function App in your subscription. Right-click the new function app, and then select Deploy to Function App.
The app builds and starts deploying. You can track its progress in the output window.
Add connection string information
In the Azure portal, go to your new function app and select Configuration from the resource menu.
On the working pane, go to Application settings. In the Connection strings section, select New connection string.
For Name, enter redisConnectionString.
For Value, enter your connection string.
Set Type to Custom, and then select Ok to close the menu.
Select Save on the configuration page to confirm. The function app restarts with the new connection string information.
Test your triggers
After deployment is complete and the connection string information is added, open your function app in the Azure portal. Then select Log Stream from the resource menu.
Wait for Log Analytics to connect, and then use the Redis console to activate any of the triggers. Confirm that triggers are being logged here.
Clean up resources
If you want to continue to use the resources you created in this article, keep the resource group.
Otherwise, if you're finished with the resources, you can delete the Azure resource group that you created to avoid charges.
Important
Deleting a resource group is irreversible. When you delete a resource group, all the resources in it are permanently deleted. Make sure that you do not accidentally delete the wrong resource group or resources. If you created the resources inside an existing resource group that contains resources you want to keep, you can delete each resource individually instead of deleting the resource group.
To delete a resource group
Sign in to the Azure portal, and then select Resource groups.
Select the resource group you want to delete.
If there are many resource groups, use the Filter for any field... box, type the name of your resource group you created for this article. Select the resource group in the results list.
Select Delete resource group.
You're asked to confirm the deletion of the resource group. Type the name of your resource group to confirm, and then select Delete.
After a few moments, the resource group and all of its resources are deleted.
Related content
Feedback
Submit and view feedback for