Implement ICacheLoader on Single Node
Note
This feature is only available in NCache Enterprise Edition.
To configure Cache Startup Loader, ICacheLoader interface needs to be implemented and then configured using NCache Web Manager. NCache uses this custom provider to load data from the configured data source either in bulk or sequentially in case of key dependency among the items. On cache startup, NCache framework iteratively calls the LoadNext() method of this custom provider until no more data remains.
For more detail on the components of Cache Loader, refer to the chapter Components of Cache Startup Loader.
Pre-Requisites
- To utilize the following APIs, include the following namespace in your
application:
Alachisoft.NCache.Runtime.CacheLoader
Alachisoft.NCache.Runtime.Caching
Alachisoft.NCache.Runtime.Dependencies
- Data being added into cache must be marked serializable.
- This should be a class library project using Microsoft Visual Studio.
- Make sure to configure the Cache Loader using NCache Web Manager on NCache cluster.
The following implementation of ICacheLoader adds 500 items of the Customer class as a bulk into the cache and then adds the remaining 500 (with key dependency) sequentially.
public class Loader : ICacheLoader
{
private SqlConnection connection;
private int dependencyCount = 500; //first 500 items to be added in bulk
private int totalCount = 1000;
private int index = 0;
// Initializing data source settings
public void Init(IDictionary parameters, string cacheId)
{
string connString = parameters["connectionString"].ToString();
connection = new SqlConnection(connString);
connection.Open();
}
// Load data from source into cache
public LoaderResult LoadNext(object index)
{
LoaderResult result = new LoaderResult();
int nextIndex = 0;
if (index != null)
nextIndex = (int)index;
for (; nextIndex < totalCount; nextIndex++)
{
Product product = new Product(nextIndex, "name:" + nextIndex.ToString());
ProviderCacheItem cacheItem = new ProviderCacheItem(product);
if (nextIndex < dependencyCount)
{
result.HasKeyDependency = false; //add in bulk
}
else if (nextIndex < dependencyCount * 2 && nextIndex > dependencyCount)
{
result.HasKeyDependency = true; //add sequentially
cacheItem.Dependency = new KeyDependency("Product: 0");
}
string key = "Product: ";
var keyvaluePair = new KeyValuePair<string, ProviderItemBase>(key, cacheItem);
result.Data.Add(keyvaluePair);
}
result.HasMoreData = false;
return result;
}
public void Dispose()
{
// Optional implementation
}
// Configure this implementation on cache
}
Important
Configure Cache Loader on NCache by referring to Configure Cache Loader in Administrator’s Guide for help.
See Also
Components of Cache Startup Loader
Sample Implementation of ICacheLoader with Distribution Hints
Data Source Providers (Backing Source)
Custom Cache Dependencies