Sunday, November 16, 2014

Redis Cache for Cats!

First read this. OK. Now that you've read that, consider a "Cat" made like so:

using System;
namespace RedisExperiment.Models
{
   public struct Cat
   {
      public DateTime BirthDay { get; set; }
      public int Lives { get; set; }
      public bool IsPurring { get; set; }
   }
}

 
 

Alright, if we have something like what follows then "You have cloned your cat!" will end up in ViewBag.Whatever.

using System;
using System.Web.Mvc;
using RedisExperiment.Models;
using StackExchange.Redis;
namespace RedisExperiment.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         Cat orginalCat = new Cat()
         {
            BirthDay = new DateTime(2011,6,7),
            Lives = 9,
            IsPurring = true
         };
         var _connection = ConnectionMultiplexer.Connect("localhost");
         IDatabase db = _connection.GetDatabase();
         db.HashSet("Cat", "BirthDay", orginalCat.BirthDay.ToString());
         db.HashSet("Cat", "Lives", orginalCat.Lives.ToString());
         db.HashSet("Cat", "IsPurring", orginalCat.IsPurring.ToString());
         Cat clone = new Cat();
         foreach (var item in db.HashGetAll("Cat"))
         {
            if (item.Name == "BirthDay") clone.BirthDay = Convert.ToDateTime(item.Value);
            if (item.Name == "Lives") clone.Lives = Convert.ToInt32(item.Value);
            if (item.Name == "IsPurring") clone.IsPurring = Convert.ToBoolean(item.Value);
         }
         if (orginalCat.Equals(clone))
         {
            ViewBag.Whatever = "You have cloned your cat!";
         } else {
            ViewBag.Whatever = "Your clone is messed up!";
         }
         return View();
      }
   }
}

No comments:

Post a Comment