Compartilhar via


My encounter with Redis Cache: getting inside session management using Azure Redis Cache.

What is caching? There are some cool examples of caching in our day-to-day life. You keep milk in the refrigerator so that you don’t need to go to the market every time you want to drink it – this is caching. You keep coins in your pocket so that you don’t have to go to the ATM every time you have to spend cash – this is caching. In our technology world, we have different types of caching too.

Redis. This is probably the most popular caching service around. And guess what, companies like Twitter, GitHub, StackOverflow, Instagram, Snapchat, Flickr are already using it in some form or the other. With all of this going around, why not take a quick lap and have a look at one small application of Redis?

For the readers who are getting started, Redis is an open-source advanced key-value cache and store. The special thing about Redis is that the keys in Redis can contain not just strings, but hashes, lists, sets, etc. Their official website (redis.io) has a ton of information if you want to read more. As some of you may know, Redis is a managed service on Azure. What this means is, Azure will give you ready-to-use features and services of Redis and you can plug-and-play them into your application. You get access to a secure, dedicated Redis cache and this is accessible from any application within Azure.

In this blog, we are going to see a scenario where Redis can manage sessions for us. First of all, to setup Redis, we have some excellent resources in our official documentation. Just do a quick brief of it if you haven’t already here. There’s also an ASP.NET Session state provider for Azure Redis cache. It’s very well documented here.
Let’s take a look at what happens within the cache once the session variables are stored. For this demo, I’m using a simple web page to start a session and display the person’s name. The first page looks like:

The first line displays the session ID, which is randomly generated by ASP.NET.

I’ve edited my web.config to tell my application to use Azure Redis cache to store session variables. These are the few lines of code to be added:

 <sessionState mode="Custom" customProvider="MySessionStateStore" timeout="10">
 <providers>
 <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="<Enter your Azure Redis Cache endpoint here>.redis.cache.windows.net" accessKey="<Enter your access key here>" />
 </providers>
 </sessionState>

(Timeout has been set to 10 min for this demo)

The code behind for the first page (which I have simply named hello.aspx) is:

 protected void Page_Load(object sender, EventArgs e)
 {
 Label1.Text= Session.SessionID; // Displays the session ID.
 string name = Session["name"] as string;
 if (name != null)
 Response.Redirect("welcome.aspx");
 }
 
 protected void nameText_TextChanged(object sender, EventArgs e) //Method to be called when we enter the name in the textbox
 {
 Session["name"] = TextBox1.Text; //We store the name in the session variable Session[“name”]
 }
 
 protected void enterButton_Click(object sender, EventArgs e) //Method to be called when we click the Enter button
 {
 string name = Session["name"] as string;
 if (name != null)
 { 
 Label2.Text = "Welcome " + name;
 Response.Redirect("welcome.aspx");
 }
 else
 Label2.Text = "Nothing entered";
 }
 

This is a straightforward piece of code. As the web page loads, I initiate my connection to Azure Redis cache through Azure client. This is achieved by using azure-cli.exe in admin mode. Have a look at this and this to know how it’s done.
Once this setup is done, we set two keys – key1 and key2 and view them. So, currently, there are 2 key-value pairs in the cache. (all the commands used here are very well documented on redis.io)

Now, as soon as I enter my name and press Enter, the welcome page loads up.

 

The cache is now populated with a new key-value pair:

Let’s see what this new entry is made of. To find out the type of key, I just enter a simple Redis command – type <key name>

And this comes out as a hash type! A hash holds field-value pairs.

Let’s play around with some hash commands now.

  • hkeys: This displays all the field names in the hash stored at the key we mention.

    As it shows, we only have one field right now, which is the “name”. If you go back to the code behind (hello.aspx), we had initiated Session[“name”] – this is where the field comes from.

  • hget: Let’s try to get the value associated with this field. The command used for that is hget.

    And something familiar comes up – the name we entered is stored in the value of this field.

 

Once 10 minutes are over, the session is completed (we had set the timeout as 10) and now if we try to refresh the Welcome page, it redirects to the home page.

This pretty much sums up the small application of Redis cache.

So, to summarize,

  • Session variables are stored in a hash type.
  • The key is of type string. The value of that key is of type hash which has field-value pairs.
  • The field holds the parameters we had passed during programming (say we stored the name in session[“name”] - the field holds the string “name”). The value of that field holds the name we had passed through the website in the textbox for name.

Hope you guys had fun reading this!

Until next time,
Saurabh Kirtani
@saurabhkirtani

Comments

  • Anonymous
    July 16, 2015
    Do you know what all the hex data is before the actual value of the "name" field?

  • Anonymous
    July 20, 2015
    RedisSessionState uses BinaryFormatter to serialize data into binary format. This should be the data appearing before "name".

  • Anonymous
    December 01, 2015
    The only thing better than using redis for sessions, is not using sessions at all. I would try to avoid them at all costs and just use caching directly instead of sessions for the same sort of purposes. The session locking that happens on each page load really hurts performance. Thanks, Matt Watson Stackify - APM for ASP.NET