NCache 4.4 - Online Documentation

Configuring Read-Through Provider

 
The following steps should be followed to configure and implement the Read-Through provider with NCache.
 
Implementing IReadThruProvider Interface
 
To implement IReadThruProvider, add following references in the provider assembly.
 
Alachisoft.NCache.Runtime.dll
 
Create a class that implements Alachisoft.NCache.Runtime.DatasourceProviders.IReadThruProvider interface and deploy it using NCache Manger. NCache framework will internally use this class to load the data from the configured data source if it is not available in the cache.
 
IReadThru Interface
 
Public void Init(System.Collections.IDictionary parameters, StringcacheId);
Public void Dispose();
Public void LoadFromSource(string key, out ProviderCacheItemcacheItem);
Public Dictionary<string, ProviderCacheItem> LoadFromSource(string[] keys);
 
Member
Description
Init
This method will be called by NCache framework on cache startup. User can use this method for performing tasks like allocating resources, acquiring connections of data source etc. This method takes as input the IDictionay instance of  arguments passed to the provider through NCache Manger (configuration settings). It allows you to pass list of parameters to provider. These parameters can be utilized in many ways. For example, connection string of a data source can be specified as a parameter. Thus, it provides a flexible way to change the data source settings while configuring it without code changes.
The other argumentCacheId specifies the cache name for which read-through is configured.
LoadFromSource
This method will be called by NCache framework if the required item is not found in cache store and NCache has to load it through configured data source. This method should contain logic to load an object from configured data source. First argument "key" refers to the key of required item. The second argument is an out parameter of type Provider CacheItem which needs to be instantiate it along with required properties Here you can associate various properties to loaded item before returning it back to NCache framework. Make sure that Provider CacheItem.Value assigned in this method is "Serializable" because NCache will later save that item to cache store  to fulfill future requests.
While implementing this method, you should take care of code thread safety as multiple Get requests can access this method for read-through.  Also do care to avoid scenarios that cause recursive infinite loops e.g. in this method a Get request with read-through on the same cache handle will cause infinite recursion.
Note: In case of Get, LoadFromSource(string key, out ProviderCacheItemcacheItem) will be called from provider while for GetBulk, LoadFromSource(string[] keys)
will be called to load items from data source.
Dispose
This method will be called by NCache framework when cache stops. You can use this method for performing tasks like releasing resources, disposing connections etc. Here you can free the resources related to data source for effective resource utilization.
 
 
In NCache, Read-Through providers are configured on cache level i.e. for clustered caches all nodes will contain provider configurations and their deployed assemblies.
 
 
Sample Code for IReadThruProvider
 
// Contains methods used to read an object by its key from the master data source.
// Contains methods used to read an object by its key from the master data source.
public class SampleReadThruProvider : IReadThruProvider
{
private SqlConnection _connection;
//Perform tasks like allocating resources or acquiring connections
 
public void Init(IDictionary parameters, string cacheId)
{
object connStringObject = parameters["connstring"];
string connString = connStringObject == null ? "" : connStringObject.ToString();
if (connString != "")
            _connection = new SqlConnection(connString);
try
{
  _connection.Open();
}
catch (Exception ex)
{
//handle exception
}
}
 
//Responsible for loading an item from the external data source.
public void LoadFromSource(string key, out ProviderCacheItem cacheItem)
{
//where LoadFromDataSource is the dummy method to load data from data source.
object value = LoadFromDataSource(key);
        cacheItem = new ProviderCacheItem(value);
        cacheItem.ResyncItemOnExpiration = true;
}
 
//Perform tasks associated with freeing, releasing, or resetting resources.
public void Dispose()
{
if (_connection != null)
            _connection.Close();
}
 
//Responsible for loading bulk of items from the external data source.
public Dictionary<string, ProviderCacheItem>LoadFromSource(string[] keys)
{
  try
  {
Dictionary<string, ProviderCacheItem> dictionary = new Dictionary<string, ProviderCacheItem>();
string key = null;
for (int index = 0; index <keys.Length; index++)
      {
          key = keys[index];
//where LoadFromDataSource is the dummy method to load data from data source.
          dictionary.Add(key, new ProviderCacheItem(LoadFromDataSource(key)));
      }
return dictionary;
  }
        catch (Exception exp)
  {
Throw;
  }
}
private object LoadFromDataSource(string key)
{
object retrievedObject = null;
// load item from your data source and populate retrieved Object
return retrievedObject;
}
}
 
After implementing and deploying this provider, direct calls can be made to NCache to get the required items. If item is not locally available in cache store, NCache will use "LoadFromSource" method in specified data access class to load items from data source.
 
Using Read-Through with Basic Operations
 
This section will explain the use of read-through provider after configuring and deploying it. NCache supports multiple read-through providers with an applications.
 
Add the following namespaces in application:
 
using Alachisoft.NCache.Web.Caching;
using Alachisoft.NCache.Runtime.DatasourceProviders;
using Alachisoft.NCache.Runtime;
 
NCache provides Alachisoft.NCache.Web.Caching.DSReadOption enum to specify Read thru option in APIs.
Multiple read-through providers can be configured through NCache. Default read-through provider will be called if specific provider name is not mentioned through API. You can also use providers other than default by using provider specific overloads of APIs.
 
  • Get Method
 
Member
Description
Get(string key, DSReadOption dsReadOption)
Get item from cache and uses default provider
Get(string  key, string providerName, DSReadOption dsReadOption)
Get item from cache and uses specified provider
 
Product product=null;
try
{
string key = "Product:1001";
object data = cache.Get(key, DSReadOption.ReadThru);
if (data != null)
    {
        product = (Product)data;
    }
}
catch (OperationFailedException exp)
{
//handle exception }
 
  • Bulk Method
 
For better understanding of the these operations review  Bulk Operations. In this scenario, use the following API
Member
Description
IDictionary GetBulk(string[] keys, DSReadOption dsReadOption)
Get bulk items from cache and uses default provider
IDictionary GetBulk(string[] keys, string providerName, DSReadOption dsReadOption)
Get bulk items from cache and uses specified provider
 
try
{
String[] keys = { "Product:1001", "Product:1002", "Product:1003", "Product:1004" };
IDictionary resultSet = cache.GetBulk(keys, DSReadOption.ReadThru);
//IDictionary contains cached keys and values
}
catch (OperationFailedException exp)
{
//handle exception
}
 
  • Using Read-Through Provider with CacheItem
 
For this scenario, use the following API.
Member
Description
CacheItem GetCacheItem(string key DSReadOption dsReadOption)
Get CacheItem from cache and uses default provider
GetCacheItem(string key, string providerName, DSReadOption dsReadOption)
Get CacheItem from cache and uses specified provider
 
string key = "Product:1001";
Product product=null;
 
try
{
CacheItem data = cache.GetCacheItem(key, DSReadOption.ReadThru);
if (data!= null)
    {
        product = (Product)data.Value;
    }
}
catch (Exception exp)
{
//handle exception
}
 
Please note that you can specify default provider through NCManager or through client.ncconf placed in config folder of NCache installation directory. If provider name is not provided in both API and client.ncconf, default provider will automatically be used.
 
<cache id="mycache" default-readthru-provider="defaultProviderName" client-cache-id="" client-cache-syncmode="optimistic" default-writethru-provider="" load-balance="True" server-runtime-context="NCACHE">
  ...
</cache>
 
CacheInitParam can also be used to specify providers.
NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
 
 
 
See Also