Sample Implementation of ICacheLoader with Distribution Hints
The following implementation of ICacheLoader
compares the distribution hints
and loads the respective data through querying. If the hint matches
“Products
”, LoadProductData()
fetches all products fulfilling the querying
criteria, which are then loaded into the cache through the node. Similar action
is taken for Customer and Orders, where the respective data is fetched and
loaded accordingly.
public class Loader : ICacheLoader
{
int ItemsPerHint = 10000;
private SqlConnection connection;
string _hint = null;
void ICacheLoader.Init(IDictionary parameters, string cacheId)
{
try
{
IDictionaryEnumerator ide = parameters.GetEnumerator();
while (ide.MoveNext())
{
//get connection string
if (ide.Key.ToString().Equals("connectionstring",
StringComparison.OrdinalIgnoreCase))
{
string connString = ide.Value.ToString();
connection = new SqlConnection(connString);
connection.Open();
}
//get distribution hints – distributionhint is a keyword
if (ide.Key.ToString().Equals("distributionhint",
StringComparison.OrdinalIgnoreCase))
{
_hint = ide.Value.ToString();
}
}
}
catch{/*handle exception*/}
}
LoaderResult ICacheLoader.LoadNext(object index)
{
if (_hint != null)
return LoadData(index);
else
return new LoaderResult();
}
protected LoaderResult LoadData(object index)
{
//compare hints and load respective data
if (_hint == "Products")
return LoadProductData(index);
else if (_hint == "Customer")
return LoadCustomerData(index);
else if (_hint == "Order")
return LoadOrderData(index);
else
return new LoaderResult();
}
protected LoaderResult LoadProductData(object index)
{
LoaderResult result = new LoaderResult();
try
{
int lastIndex = 0;
if (index != null)
{
lastIndex = (int)index;
}
//fetch specific data based on query
SqlCommand command = new SqlCommand("SELECT * FROM Products WHERE ProductID > " +
lastIndex.ToString() + " AND ProductID< " + (lastIndex+10).ToString(), connString);
SqlDataReader reader = command.ExecuteReader();
int nextLimit = 50 + lastIndex;
string key = "Product_"+ product.ProductID;
while (reader.Read() && lastIndex < nextLimit && lastIndex < ItemsPerHint)
{
Product product = new Product();
product.ProductName = reader["ProductName"].ToString();
product.ProductID = Convert.ToInt32(reader["ProductID"]);
ProviderCacheItem providerItem = new ProviderCacheItem(product);
result.Data.Add(key, providerItem);
lastIndex++;
}
if (lastIndex < ItemsPerHint)
{
result.UserContext = lastIndex;
result.HasMoreData = true;
}
}
catch{/*handle exception*/}
return result;
}
protected LoaderResult LoadCustomerData(object index)
{
//perform operations
return new LoaderResult();
}
protected LoaderResult LoadOrderData(object index)
{
//perform operations
return new LoaderResult();
}
}
}
See Also
Components of Cache Startup Loader
Sample Implementation of ICacheLoader on Single Node