.NET · Azure

Redis Cache on Azure

This post is a superfast guide to using Redis Cache on Azure with a small sample project using StackExchange.Redis.

You can download the project here.

On your Azure portal click on “New -> Redis Cache” and create a DNS name, a Resource name and select your plan.

RedisCache1

In Visual Studio, create a new Console Application. With NuGet Package manager you can get StackExchange.Redis. (PM> Install-Package StackExchange.Redis)

RedisCache2

On your portal you can click “Show access keys” to get your entire connection string for StackExchange.Redis. We will use that to connect to our Cache.

RedisCache3

In your Console Application you will have the following code:

RedisCache4

First you need to connect to your Redis Cache on Azure. For that you will use the ConnectionMultiplexer. This is fully thread-safe and should only be initiated once. You could either use Connect() or ConnectAsync() passing in a connectionstring or configuration options.

Now you need to access your Redis database, you do that with conn.GetDatabase()

In this small sample I need to get all keys stored in my database, and for that we will need to have a IServer instance. Use conn.GetServer(“<your-server>.redis.cache.windows.net:6380”).

Now you are done.

To write to your cache: db.StringSet(Key, Value, Timespan(How long this will live))
To get data from you cache: dg.StringGet(key) or db.StringGetWithExpiry(key).

Thanks for reading.