Monday, August 31, 2015

Sitecore Caching Revisited

Previously I wrote about using the Sitecore Custom Cache.  Unfortunately I don’t think I put enough detail in that post.  Some may have been a little confused by it. 

Creating the Cache

Really creating a cache is almost too easy, you simply create a class that inherits from CustomCache and then implement SetObject  and GetObject as I said in my previous post.
public class MyCustomCache : CustomCache
 {
     public MyCustomCache(string name, long maxSize)
         : base(name, maxSize)
     {
     }

     public void SetObject(string key, object value)
     {
         base.SetObject(key, value, Sitecore.Reflection.TypeUtil.SizeOfObject());
     }

     public new object GetObject(object key)
     {
         return base.GetObject(key);
     }
 }

The Cache Manager

The problem with stopping here is though we have the cache we do not have an instance of it created.  This is also a very simple task.  The easiest way to implement it is just to create a static instance of it somewhere.  More properly though would be to create a static cache manager. 
public static class MyCacheManager
{
    private static readonly MyCustomCache Cache = new MyCustomCache(
        "My.NameSpace.Custom.Cache",
        StringUtil.ParseSizeString(Sitecore.Configuration.Settings.GetSetting("My.Custom.Cache.Size.Setting.Name""5MB")));
 
    public static object Get(string key)
    {
        return Cache.GetObject(key);
    }
 
    public static void Set(string key, object value)
    {
        Cache.SetObject(key, value);
    }
}

Clearing the Cache

It really is that easy.  It may be wise though to add a cache clearing mechanism as well maybe add a new static method to the manager.
public static void Clear()
{
    Cache.Clear();
}


Of course you still need to trigger this call using the Sitecore Pipelines which is also very easy, just add the call anywhere Sitecore normally clears the cache.

No comments:

Post a Comment