In our last article, Part 1: How to Implemented a CustomCache, we created a CustomCache object of SOLR search results.
We need a way of creating a unique key for each of these caches. The easiest way to do this is just to take the entire request object, encode it (MD5), and use that.
Getting The Hash From An Object
For our example, we have created a request object to specify our search parameters for a SOLR content search.
We want to use this as a key for our CustomCache we created in Part 1. Essentially, if the key does not exist in the Sitecore cache, we want to execute the search. If it does not, we want to get the cached results and use those.
public static string GetMD5Hash(this object instance)
{
return instance.GetHash();
}
public static string GetHash(this object instance) where T : HashAlgorithm, new()
{
T cryptoServiceProvider = new T();
return ComputeHash(instance, cryptoServiceProvider);
}
private static string ComputeHash(object instance, T cryptoServiceProvider) where T : HashAlgorithm, new()
{
DataContractSerializer serializer = new DataContractSerializer(instance.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
serializer.WriteObject(memoryStream, instance);
cryptoServiceProvider.ComputeHash(memoryStream.ToArray());
return Convert.ToBase64String(cryptoServiceProvider.Hash);
}
}
How To Use
Below is a chunk of code I have pulled from my Search Query Service class. I first take the request object parameter searchRequest and pass it into the above code to get the MD5 Key.
If that key exists in our custom cache, we can retrieve the cached results and use that. If it does not exist, we will run a search against the index and cache those results using the unique MD5 key.
var md5Key = ObjectHashExtensions.GetMD5Hash(searchRequest);
var cache = SearchResultsCacheManager.GetCache(md5Key);
if (cache != null)
{
return cache.SearchResultItems;
}
var results = _searchService.Search(searchRequest);
var toCache = new SearchResults { SearchResultItems = results };
SearchResultsCacheManager.SetCache(md5Key, toCache, Settings.GetTimeSpanSetting("SearchResultsCaching.ScavengeInterval", "00:30:00"));
return results;
Next Steps
So far we have a CustomCache implementation who's entries are matched with a unique key created from a request object. Let's now look at how to clear the cache by listening to the publish pipeline in Part 3: How to Clear the Sitecore CustomCache on Publish.