Sunday, November 16, 2014

Redis Cache!

using System;
using System.Web.Mvc;
using StackExchange.Redis;
namespace RedisExperiment.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         var _connection = ConnectionMultiplexer.Connect("localhost");
         IDatabase db = _connection.GetDatabase();
         db.StringSet("MyName", "Tom", TimeSpan.FromHours(13));
         ViewBag.Whatever = db.StringGet("MyName");
         return View();
      }
   }
}

...is about the easiest example I can think for how to use Redis Cache. In the above code for an ASP.NET MVC C# Controller, ViewBag.Whatever is gonna end up with "Tom" in it. If you take out the middlemost line of code with StringSet in it, then "Tom" will end up in ViewBag.Whatever anyways if you run the code again within, I suppose, thirteen hours. If you were to run the code more than thirteen hours later or you were to never have the middlemost line of code in the code above to begin with to set a value for MyName then ViewBag.Whatever would just end up with null inside. Make sense? The code above is largely a recreation of code displayed by Shawn Weisfeld at a talk he gave on Monday night at the Austin .NET User Group. In his example he used "Shawn" and not "Tom" though as you might imagine. Anyways... something Shawn didn't really touch on is how sexy this stuff is in the Azure space (where I've never worked personally) where there can be no reliance on using the traditional cache or session as your application will straddle many machines instead of being hosted on just one. I think this is the real reason most of us care about Redis. I haven't had to go there myself and I haven't used it at my work. I have just played with Redis for the first time in the past few days now that I've been exposed to it. You need two things to get this stuff working if you want to spin up an easy example like the one I have above:

  1. You need StackExchange.Redis as a reference in your ASP.NET project to make the lines of code above not be angry with you. You may get that here, or you may just pull it from NuGet like so to have it end up in your packages folder:
    Install-Package StackExchange.Redis

  2. You need an actual server to talk to. You may get that here or you may also get this from NuGet like so:
    Install-Package Redis-64
    "localhost" seems to find the server just fine which will by default run on port 6379. The server will be an executable called redis-server.exe and if you get it the NuGet way it will just end up in your packages folder. If you double click you should see a console app sitting open on your desktop. Just keep this up to experiment.

There was more to Shawn's presentation than just what I offer here. Perhaps I'll write more later. Dunno.

No comments:

Post a Comment