How to Use Custom Dependency in Distributed Cache?

Today, web applications are increasingly using distributed cache for boosting performance and scalability by caching frequently used data so as to reduce expensive database trips. Distributed cache spans and synchronizes over multiple cache servers to let you scale in a linear fashion.

A good distributed cache usually has a Cache Dependency feature to let you expire cached items when something they depend on changes. A Cache Dependency can be key-based, file-based, or database-based. So, in essence you can specify a cached item to be dependent on another item in the cache (key-based), a file in the file system (file-based), or a row or a dataset in a SQL Server database (database-based). And, when data in any of these sources changes, your cached item is automatically removed from the cache because the “dependency was expired”. This allows you to keep your cached data fresh and correct always.

This is all well and good but what if you want your cached items to be dependent on data in data sources other than the ones mentioned above. For example, you might have an RSS feed (Rich Site Summary) that provides you data changes. And, you have your own program to read this feed and want to expire certain cached items based on whatever data changes you see in the RSS feed. There are many other similar situations where the data source is “custom”.

So, to handle these situations, a good distributed cache should provide you the flexibility to implement your own Custom Cache Dependency for your cached items so they can be expired when data in your custom data source changes.

Download NCache free trial - Extremely fast and scalable in-memory distributed cache

NCache provides such a Custom Cache Dependency feature. NCache is a powerful distributed cache for all kinds of .NET and Java applications. And, NCache lets you implement your own custom dependencies. Let me demonstrate how easily you can implement a custom dependency with NCache below. Here are the steps you have to take:

  1. Add using Alachisoft.NCache.Runtime.Dependencies; reference to your custom dependency implementation.
  2. NCache provides extensible abstract class named as ExtensibleDependency which is base class of all dependencies. You just have to inherit your custom dependency class from ExtensibleDependency and then just override its HasChanged property. When this property will return true, than item dependent item will be expired from cache.

Here is a full example of custom dependency implementation in which if available units of a specified product are less than 100 then dependency change will be triggered.

using Alachisoft.NCache.Runtime.Dependencies;

[Serializable]
public class CustomDependency : ExtensibleDependency
{
   private string _connString;
   private int _productID;

   public override bool Initialize(){ return false; }

   public CustomDependency(int productID, string connStr)
   {

     _connString = connStr;
     _productID = productID;

   }

   internal bool DetermineExpiration()
   {
     if (GetAvailableUnits(_productID) < 100)
            return true;
     return false;
   }

   internal int GetAvailableUnits(int productID)
   {
     OleDbDataReader reader=null;
     OleDbConnection connection=
                      new OleDbConnection(_connString);
     connection.Open();
     int availableUnits=-1;
     try
     {
        OleDbCommand cmd = connection.CreateCommand();

        cmd.CommandText =
        String.Format(CultureInfo.InvariantCulture,
        "Select UnitsInStock From Products" +
        " where ProductID = {0}", productID);
        reader = cmd.ExecuteReader();

        if (reader.Read())
        {
          availableUnits =
          Convert.ToInt32(reader["UnitsInStock"].ToString());
        }

        reader.Close();
        return availableUnits;
     }
     catch (Exception)
     {
         return availableUnits;
     }
   }

   public override bool HasChanged
   {
     get
      {
         return DetermineExpiration();
      }
   }
}
  1. Once you implemented your custom dependency and deployed it with NCache service, all you need is to register this dependency with dependent cache items in your application wherever needed.
using Alachisoft.NCache.Web.Caching; //add namespace

//Add following code in your application
Cache _cache = NCache.InitializeCache("myCache");

string connString =
       "Provider=SQLOLEDB;Data Source=localhost;
        User ID=sa;password=;Initial Catalog=Northwind";

CustomDependency hint = new CustomDependency(123, connString);

_cache.Add("Product:1001", "Value", new CacheDependency(hint),
       Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 10),
       Alachisoft.NCache.Runtime.CacheItemPriority.Default);

Now when data in your custom data source changes, NCache expires the dependent cached items automatically from cache. NCache is responsible for running your custom dependency code so you don’t need to worry about implementing your own separate program and hosting it in some reliable process. Try and explore it for your application specific scenarios.

Download NCache Trial | NCache Details

This entry was posted in Cache dependency, Custom Dependency, Distributed Cache, Distributed caching and tagged , , , . Bookmark the permalink.

2 Responses to How to Use Custom Dependency in Distributed Cache?

  1. I’m not that much of a online reader to be honest but your
    blogs really nice, keep it up! I’ll go ahead and bookmark your
    site to come back later on. Cheers

  2. Alvaro says:

    Everything is very open with a very clear
    explanation of the challenges. It was really informative.
    Your site is very helpful. Thank you for sharing!

Leave a Reply

Your email address will not be published. Required fields are marked *


4 × seven =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>