Try Playground
Show / Hide Table of Contents

Using Write-behind Cache

This section explains the use of Write-behind mode after deploying and configuring the Write-Through provider. Write-behind updates the data source asynchronously after updating the cache.

Note

Write-Behind is [Deprecated] for NCache Java.

Prerequisites

  • .NET
  • Java
  • Legacy API
  • To learn about the standard prerequisites required to work with all NCache server-side features please refer to the given page on Server Side API Prerequisites.
  • For API details refer to: CacheItem, Get, Insert, IWriteThruProvider, Remove, InsertBulk, RemoveBulk, InsertAsync, RemoveAsync.
  • To learn about the standard prerequisites required to work with all NCache server-side features please refer to the given page on Server Side API Prerequisites.
  • For API details refer to: CacheItem, insert, WriteThruProvider, remove, insertBulk, removeBulk, insertAsync, removeAsync.
  • Create a new Console Application.
  • Make sure that the data being added is serializable.
  • Add NCache References by locating %NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
  • Include the Alachisoft.NCache.Runtime.DatasourceProviders and Alachisoft.NCache.Web.Caching namespaces in your application.

Add/Update with Write-behind

You can add/update cache items with or without callback in the cache along with Write-behind enabled. Adding with callback notifies you on the type of event occurred which you register.

Add without Callback Method

The following example adds an item in the cache with Write-behind enabled, using the Insert() method. Using this method, if an item is already present in the cache, the new value overwrites the old value.

  • .NET
  • Java
  • Legacy API
// Pre-Condition: Cache is already connected

// Specify the key of the cacheItem
Product product = FetchProductByProductID(1001);
string key = $"product:ProductID";
var cacheItem = new CacheItem(product);

// Enable write through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;

// Add item in the cache with Write-behind
cache.Insert(key, cacheItem, writeThruOptions);
// Pre-Condition: Cache is already connected

// Specify the key of the cacheItem
String key = product.getProductID();
var cacheItem = new CacheItem(product);

// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteBehind);

// Add item in the cache with Write-behind
cache.insert(key,cacheItem,writeThruOptions);
string key = "Customer:David:1001";
CacheItem cacheItem = new CacheItem(new Product());
cache.Add(key, cacheItem, DSWriteOption.WriteBehind, null);
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

Add with Callback Method

The following example adds an item in the cache with callback registered and event type of ItemAdded with Write-behind enabled.

  • .NET
  • Java
  • Legacy API
// Specify the key of the cacheItem
Product product = FetchProductByProductID(1001);
string key = $"product:ProductID";
var cacheItem = new CacheItem(product);

// Enable write through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemAdded);

// Add item in the cache with Write-behind
cache.Insert(key, cacheItem, writeThruOptions);
// Specify the key of the cacheItem
String key = product.getProductID();
var cacheItem = new CacheItem(product);

// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteBehind);

// assuming that DataSourceModified has been implemented as interface before
EnumSet<EventType> eventTypes = EnumSet.of(EventType.ItemAdded);
writeThruOptions.setDataSourceModificationListener(dataSourceModifiedListener, eventTypes);

// Add item in the cache with Write-behind
cache.insert(key,cacheItem,writeThruOptions);
protected void OnDataSourceItemsAdded(IDictionary iDict)
{
    //Perform appropriate actions upon response
}

private void AddTest()
{
    string key = "Customer:David:1001";
    CacheItem cacheItem = new CacheItem(new Product());
    cache.Add(key, cacheItem, DSWriteOption.WriteBehind, OnDataSourceItemsAdded);

}

Remove Existing Data with Write-behind

The following example removes the item from the cache with Write-behind enabled, using the Remove method, corresponding to the key provided as well as from the data source and registers the events for the operation.

  • .NET
  • Java
  • Legacy API
// Specify the key of the item
string key = "Product:1001";

// Enable write through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemRemoved);

// Remove the item corresponding to the key with write-through enabled
cache.Remove(key, null, null, writeThruOptions);
// Specify the key of the item
String key = "Product:1001";

// Enable write through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteBehind);

EnumSet<EventType> eventTypes = EnumSet.of(EventType.ItemRemoved);
writeThruOptions.setDataSourceModificationListener(dataSourceModifiedListener, eventTypes);

// Remove the item corresponding to the key with write-through enabled
cache.remove(key,writeThruOptions,Product.class);
protected void OnDataSourceItemsRemoved(IDictionary iDict)
{
    //Perform appropriate actions upon response
}

private void DeleteTest()
{
    string key = "Customer:David:1001";

    cache.Delete(key, DSWriteOption.WriteBehind, OnDataSourceItemsRemoved);
}

Bulk Operations

Add/Update Bulk Items with Write-behind

The following example adds bulk items in the cache with Write-behind enabled, using the InsertBulk() method. If the items are already present in the cache, new values overwrite the existing values.

  • .NET
  • Java
  • Legacy API
// Fetch all products from database
Product[] products = FetchProductsFromDB();

var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemAdded);
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemUpdated);

IDictionary<string, CacheItem> dictionary = new Dictionary<string, CacheItem>();

foreach(var product in products)
{
  string key = $"Product:{product.ProductID}";
  var cacheItem = new CacheItem(product);

  dictionary.Add(key, cacheItem);
}
IDictionary<string, Exception> keysFailedToUpdate = cache.InsertBulk(dictionary, writeThruOptions);
// Fetch all products from database
Product[] products = fetchProductsFromDB();

var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteBehind);

EnumSet<EventType> eventTypes = EnumSet.of(EventType.ItemAdded);
eventTypes.add(EventType.ItemUpdated);
writeThruOptions.setDataSourceModificationListener(dataSourceModifiedListener,eventTypes);

HashMap<String,CacheItem> distributedMap = new HashMap<String, CacheItem>();
for (var product: products) {
  String key = ;
  var cacheItem = new CacheItem(product);
  distributedMap.put(key,cacheItem);
}

Map<String,Exception> keysFailedToUpdate = cache.insertBulk(distributedMap,writeThruOptions);
protected void OnDataSourceItemsUpdated(IDictionary iDict)
{
    //Perform appropriate actions upon response
}

private void BulkUpdateTest()
{

      String[] key = { "Customer:David:1001", "Customer:Paul:1002", "Customer:Dave:1003", "Customer:Mathew:1004" };

      //create new  custom objects for above mentioned keys of Product type
      CacheItem[] data = cache.GetCacheItems(keys.Length);

      IDictionary failedItems = cache.InsertBulk(keys, data, DSWriteOption.WriteBehind, OnDataSourceItemsUpdated);

}

Remove Existing Items with Write-behind

The following example removes a bulk of items from the cache with Write-behind enabled, using the RemoveBulk() method.

  • .NET
  • Java
  • Legacy API
// Get Keys
Product[] products = FetchProductsFromDB();

// Specify keys to remove from cache
string[] keys = new string[products.Length];
int index = 0;

foreach (var product in products)
{
  keys[index] = $"Product:{product.ProductID}";
  index++;
}

// Create dictionary to store removed items
IDictionary<string, Product> removedItems = new Dictionary<string,Product>();

var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemRemoved);

// Remove items with Write-behind enabled
cache.RemoveBulk(keys, out removedItems, writeThruOptions);
// Get Keys
Product[] products = fetchProductsFromDB();

// Specify keys to remove from cache
String[] keys = new String[products.length];
int index = 0;
for (var product: products) {
  keys[index] = "Product" + product.getProductID();
  index++;
}
// Create dictionary to store removed items
Map<String,Product> removedItems = new HashMap<String,Product>();

var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteBehind);

EnumSet<EventType> eventTypes = EnumSet.of(EventType.ItemRemoved);
writeThruOptions.setDataSourceModificationListener(dataSourceModifiedListener,eventTypes);

// Remove items with Write-behind enabled
cache.removeBulk(Arrays.asList(keys),writeThruOptions,Product.class);
protected void OnDataSourceItemsRemoved(IDictionary iDict)
{
    //Perform appropriate actions upon response
}

private void BulkDeleteTest()
{

      String[] key = { "Customer:David:1001", "Customer:Paul:1002", "Customer:Dave:1003", "Customer:Mathew:1004" };

      IDictionary failedItems = cache.DeleteBulk(keys, DSWriteOption.WriteBehind, OnDataSourceItemsRemoved);
        //verify items deleted from the main source
}
Note

Use the method OnDataSourceItemsRemoved() to perform operations after data removal from the cache.

Asynchronous Operations

Add/Update Item with Write-behind

The following example adds item asynchronously in cache with Write-behind enabled, using the InsertAsync() method.

  • .NET
  • Java
  • Legacy API
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);

// Generate a unique cache key for this product
string key = $"Product:{product.ProductID}";
var cacheItem = new CacheItem(product);

// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemAdded);

// Add Product object to cache
Task task = cache.InsertAsync(key, cacheItem, writeThruOptions);
// Get product from database against given product ID
Product product = fetchProductFromDB(1001);

// Generate a unique cache key for this product
String key = "Product:" + product.getProductID();
var cacheItem = new CacheItem(product);

// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteBehind);

EnumSet<EventType> eventTypes = EnumSet.of(EventType.ItemAdded);
writeThruOptions.setDataSourceModificationListener(dataSourceModifiedListener,eventTypes);

// Add Product object to cache
FutureTask task = cache.insertAsync(key,cacheItem,writeThruOptions);
protected void OnDataSourceItemsUpdated(IDictionary iDict)
{
    //Perform appropriate actions upon response
}

private void AsyncUpdateTest()
{
    Cache mycache = NCache.InitializeCache("myreplicatedcache");

    string key = "Customer:David:1001";
    CacheItem cacheItem = new CacheItem(new Product());
    cacheItem.SubGroup = "Async-WriteThru-Test";

    cache.InsertAsync(key, cacheItem, DSWriteOption.WriteBehind, OnDataSourceItemsUpdated);

}

Remove the Item with Write-behind

The following example removes existing items asynchronously from the cache with Write-behind enabled, using the RemoveAsync() method.

  • .NET
  • Java
// Unique cache key of product to remove
string key = $"Product:{product.ProductID}";

// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemRemoved);

// Asynchronously remove items from cache
Task<Product> task = cache.RemoveAsync<Product>(key, writeThruOptions);
// Unique cache key of product to remove
String key = "Product:" + product.getProductID();

// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteBehind);

EnumSet<EventType> eventTypes = EnumSet.of(EventType.ItemRemoved);
writeThruOptions.setDataSourceModificationListener(dataSourceModifiedListener,eventTypes);

// Asynchronously remove items from cache
FutureTask<Product> task = cache.removeAsync(key,writeThruOptions,Product.class);

Use Data Structures with Write-behind

The following example uses different data structures with Write-behind enabled, on the specified item.

  • .NET
  • Java
// Specify the key of the item
string key = "Product:1001";
var dataTypeAttributes = new DataTypeAttributes();
var writeThruOptions = new WriteThruOptions(WriteMode.WriteBehind, WriteThruProviderName);

switch(mainMenu)
{
  case mainMenu.GetDistributedCounter:
    // Modify or add count of the corresponding item with write thru enabled
    var distributedCounter = cache.DataTypeManager.CreateCounter("counter", dataTypeAttributes, 0, writeThruOptions);

    // perform operations on counter
    break;
  case mainMenu.GetDistributedDictionary:
    // Modify or add dictionary of the corresponding item with write thru enabled
    var distributedDictionary = cache.DataTypeManager.CreateDictionary<string, int>(key, dataTypeAttributes, writeThruOptions);

    // perform operations on dictionary
    break;
  case mainMenu.GetDistributedList:
    // Modify or add the list of the corresponding item with write thru enabled
    var distributedList = cache.DataTypeManager.CreateList<int>("list", dataTypeAttributes, writeThruOptions);

    // perform operations on list
    break;
  case mainMenu.GetDistributedQueue:
    // Modify or add the queue of the corresponding item with read thru enabled
    var distributedQueue = cache.DataTypeManager.CreateQueue<int>("queue", dataTypeAttributes, writeThruOptions);

    // perform operations on queue
    break;
  case mainMenu.GetDistributedHashSet:
    // Modify or add the HashSet of the corresponding item with read thru enabled
    var distributedHashSet = cache.DataTypeManager.CreateHashSet<int>("hashset", dataTypeAttributes, writeThruOptions);

    // perform operations on hashset
    break;
}
// Specify the key of the item
String key = "Product:1001";
DataStructureAttributes dataStructureAttributes = new DataStructureAttributes();

// Specify the WriteThruOptions
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteBehind);
writeThruOptions.getWriteThruOptions().setProviderName(WriteThruProviderName);

switch(mainMenu) {
  case GetDistributedCounter:
    // Modify or add counter of the corresponding item with write thru enabled
    Counter distributedCounter = cache.getDataStructuresManager().createCounter("counter", 0, dataStructureAttributes, writeThruOptions);

    // Perform operations on counter
    break;
  case GetDistributedDictionary:
    // Modify or add dictionary of the corresponding item with write thru enabled
    DistributedMap<String,Integer> distributedMap = cache.getDataStructuresManager().createMap<String,Integer>(key, dataStructureAttributes, writeThruOptions);

    // Perform operations on dictionary
    break;
  case GetDistributedList:
    // Modify or add list of the corresponding items with write thru enabled
    DistributedList<String,Integer> distributedList = cache.getDataStructuresManager().createList<String,Integer>("list", dataStructureAttributes, writeThruOptions);

    // Perform operations on list
    break;
  case GetDistributedQueue:
    // Modify or add the queue of the corresponding item with write thru enabled
    DistributedQueue<String,Integer> distributedQueue = cache.getDataStructuresManager().createQueue<String,Integer>("queue", dataStructureAttributes, writeThruOptions);

    // Perform operations on queue
    break;
  case GetDistributedHashSet:
    // Modify or add the HashSet of the corresponding item with write thru enabled
    DistributedHashSet<String,Integer> distributedHashSet = cache.getDataStructuresManager().createHashSet<String,Integer>("hashset", dataStructureAttributes, writeThruOptions);

    // Perform operations on hashset
    break;
}

Additional Resources

NCache provides sample application for Write-behind on GitHub.

See Also

.NET: Alachisoft.NCache.Runtime namespace.
Java: com.alachisoft.ncache.runtime.datasourceprovider namespace.

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top