Navigate / search

Caching in Azure Function – how you can use Redis

I believe that you should know that Microsoft has prepared some set of components that can be used for integration purposes. You are able to consume the following services in our function: Azure Storage, Azure Event Hubs, Azure Service Bus, Azure Mobile Apps, Azure Cosmos DB, Azure Notification Hubs, Twilio, SendGrid. On the one hand this list is not so big. On the other one you can address with those services a lot of typical scenarios. But sometimes you need to do something more.

Today I would like to share with how easily you can use Redis cache in Azure Function. You should start thinking what for we need to do that. Probably you heard that Azure Functions should be stateless, atomic, small, fast, … But sometimes you need to do something that violate those rules.

Let’s come back to code. Before we will be able to start we need to install Redis in Azure. It is very easy – just few clicks. Then we need to add Redis connection string to our Function App (Platform features -> Application Settings -> Connection strings):

And we are almost there. We can come back to software development. First thing that we should do is adding nuget reference to StackExchange.Redis. To do that we need to create new project.json file in folder with our function. And in that file we need to point out which version of StackExchange.Redis should be used. Finally, your file should look like the following:

{
  "frameworks": {
    "net46":{
      "dependencies": {
        "StackExchange.Redis": "1.2.6"
      }
    }
  }
}

And you should be able to see the following image in your web browser:

In the last step you need just to add code that will connect to Redis and then store and read data from cache.

using System.Net;
using StackExchange.Redis;
public static HttpResponseMessage Run(HttpRequestMessage req, TraceWriter log)
{
  // Connecting to Redis
  var connString = System.Configuration.ConfigurationManager.ConnectionStrings["RedisConnectionString"].ConnectionString;
  var cache = ConnectionMultiplexer.Connect(connString).GetDatabase();
  
  // Redis usage
  var currentData = (int)cache.StringGet("ExecutionCount");
  currentData++;
  cache.StringSet("ExecutionCount", currentData);

  return req.CreateResponse(HttpStatusCode.OK, "Execution count: " + currentData);
}

And you can try to test your function. Probably you noticed that code from example will count execution of our function.

Leave a comment

name*

email* (not published)

website