onsdag den 19. februar 2014

Create a custom Sitecore cache

I have been experimenting with creating a custom Sitecore cache, to be able to cache the result of some calculations that happens all the time.

In this case, we happen to quite often lookup which of the sites defined in Sitecore, that matches a certain criteria (has certain sub items).

In solutions with many sites, this quickly starts to slow the solution down - but there is a simple solution, which is caching the result :)

So first, we have to implement the cache, which requires two classes - the cache (called SiteCache) and a cache manager (called SiteCacheManager).

Here is the code for the SiteCache:

internal class SiteCache : CustomCache
{
    public SiteCache(string name, long maxSize) : base(name, maxSize)
    {
    }

    public bool IsSiteInCache(string siteName)
    {
        object obj = GetObject(siteName);

        return obj != null;
    }

    public void AddSiteToCache(string siteName)
    {
        SetObject(siteName, true, sizeof(bool));
    }
}

And here is the code for the SiteCacheManager

internal static class SiteCacheManager
{
    private static readonly SiteCache Cache = new SiteCache("SiteCache", StringUtil.ParseSizeString("100KB"));

    public static bool IsSiteInCache(string siteName)
    {
        return Cache.IsSiteInCache(siteName);
    }

    public static void AddSiteToCache(string siteName)
    {
        Cache.AddSiteToCache(siteName);
    }

    public static void Clear()
    {
        Cache.Clear();
    }
}

The way it works is pretty simple, since the manager is static, as soon as Sitecore starts, it creates a new instance of the SiteCache cache.
Then, to use this, we create a simple function to test if sites are valid:

public bool IsSiteValid(string siteName)
{
    if (SiteCacheManager.IsSiteInCache(siteName))
    {
        return true;
    }

    bool siteValid = RunSiteTest(siteName);

    if (siteValid)
    {
        SiteCacheManager.AddSiteToCache(siteName);
    }

    return siteValid;
}

This way, we always look in the cache first, and if the site isn't there, we do the normal tests, and if the result is that the site is valid, we add it to the cache, so we can avoid the test the next time.

The reason we do this, is because the cache might have been flushed, so we need to always do the check if the site is missing from the cache.

So this works best, if most of the things you test on is valid - if most of the sites in the solution for this is returning false from the test, the amount of time saved will be minimal.

Ingen kommentarer:

Send en kommentar