• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

Update/Insert Existing Data in Cache

NCache provides the Insert method and its overloads to facilitate updating objects in the cache. While it overwrites data for existing items, it also adds the item to the cache if the key does not exist in the cache.

Note

This feature is also available in the NCache Community Edition, except for asynchronous operations.

Prerequisites

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: ICache, CacheItemVersion, CacheItem, Insert, Get, InsertBulk, InsertAsync.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, CacheItemVersion, CacheItem, get, insert, insertBulk, insertAsync.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, CacheItem, CacheItemVersion, insert, insert_bulk, insert_async, get.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, CacheItemVersion, CacheItem, get, insert, insertBulk.
  • Install either of the following NuGet packages in your .NET client application:
    • Enterprise: Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
    • Professional: Install-Package Alachisoft.NCache.Professional.SDK -Version 4.9.1.0
  • 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.Web.Caching namespace in your application.
  • To learn more about the NCache Legacy API, please download the NCache 4.9 documents available as a .zip file on the Alachisoft Website.

Update Object in Cache

You can update a custom object in the cache using various overloads of the Insert method. This returns a CacheItemVersion.

Important
  • If the key already exists, it will overwrite the existing cache item with the same key.
  • If the key does not exist, the operation adds the item to the cache instead.
Note

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

The following example gets the values of an existing object and inserts it against the same key into the cache. If the key does not exist, it adds it to the cache.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";

// Get updated customer from database against given customer key
Customer customer = FetchCustomerFromDB(customerKey);

// Insert Customer object to cache
CacheItemVersion version = cache.Insert(customerKey, customer);

// Item updated in cache successfully
// Precondition: Cache is already connected

// Get updated product from database against given product ID
Product product = fetchProductFromDB(1001);

// Insert Product object to cache
CacheItemVersion version = cache.insert("1001", product);

// Item updated in cache successfully
# Precondition: Cache is already connected

# Get updated product from database against given product ID
product = fetch_product_from_db(1001)

# Generate a unique cache key for this product
key = "Product:" + product.get_product_id()

# Insert Product object to cache
version = cache.insert(key, product)

# Item updated in cache successfully
// Precondition: Cache is already connected

//Get updated product from database against given product ID
product = await this.fetchProductFromDB(1001);

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

// Insert Product object to cache
var version = await this.cache.insert(key, product);

// Item updated in cache successfully
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected

string customerKey = $"Customer:ALFKI";

// Get updated customer from database against given customer key
Customer customer = FetchCustomerFromDB(customerKey);

// Insert Customer object to cache
CacheItemVersion version = cache.Insert(customerKey, customer);

// Item updated in cache successfully

Update Object With Expiration

CacheItem is a custom class provided by NCache that can be used to add data to the cache and also lets you set additional specifications associated with an object as properties of this class. The CacheItem is updated in the cache against a unique key.

Important
  • If the key already exists, it will overwrite the existing cache item with the same key.
  • If the key does not exist, the operation adds the item to the cache instead.

The following example gets updated values of an existing CacheItem and inserts it against the same key into the cache. If the key does not exist, it adds it to the cache.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";

// Get the customer from the database
Customer customer = FetchCustomerFromDB(customerKey);

// Update Customer's Phone
customer.Phone = "0921-12 34 65";

// Create CacheItem
CacheItem cacheItem = new CacheItem(customer);
cacheItem.Expiration = new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5));

// Update customer in DB and Cache
if (UpdateDB(customer))
{
    cache.Insert(customerKey, cacheItem);
}
// Precondition: Cache is already connected
String customerKey = "ALFKI";

// Get the customer from the database
Customer customer = fetchCustomerFromDB(customerKey);

// Update Customer's Phone
customer.setPhone("0921-12 34 65");

// Create CacheItem
CacheItem cacheItem = new CacheItem(customer);
cacheItem.setExpiration(new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5)));

// Update customer in DB and Cache
cache.insert(customerKey, cacheItem);
# Precondition: Cache is already connected
# Get the customer from the database
product = fetch_product_from_db()

# Generate a unique cache key for this product
key = "Product:" + product.get_product_id()

# Create a new CacheItem for this product
# You can OPTIONALLY specify multiple properties e.g.Priority, Expiration
# These properties are explained in successive chapters
cache_item = ncache.CacheItem(product)

# Insert CacheItem to cache
version = cache.insert(key, cache_item)
// Precondition: Cache is already connected
// Get the customer from the database
product = await this.fetchProductFromDB();

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

// Create a new CacheItem for this product
// You can OPTIONALLY specify multiple properties e.g. Priority, Expiration
// These properties are explained in successive chapters
var cacheItem = new ncache.CacheItem(product);

// Insert CacheItem to cache
var version = await this.cache.insert(key,cacheItem);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected

string customerKey = $"Customer:ALFKI";

// Get the customer from the database
Customer customer = FetchCustomerFromDB(customerKey);

// Update Customer's Phone
customer.CustomerPhone = "0921-12 34 65";

CacheItem cacheItem = new CacheItem(customer);
cache.Insert(customerKey, customer, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), CacheItemPriority.Default);

Update Bulk Items in Cache

InsertBulk updates an array of Cache​Item to the cache against the corresponding key. The method returns a dictionary of all the keys that failed to update, along with the failure reason.

Important

If any keys fail to update, their reasons of failure will be returned as an IDictionary.

The following code example fetches an array of products (of Customer type) from the database. The products are then inserted to the cache as a dictionary of keys and CacheItem using InsertBulk.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
// Create an array of all Customer Keys
String[] keys = new String[]
{
    "Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
};

// Get items from cache
IDictionary<string, Customer> itemsFetched = cache.GetBulk<Customer>(keys);

// Create a dictionary to store updated items
IDictionary<string, CacheItem> itemsUpdated = new Dictionary<string, CacheItem>();

// Update postal codes of dictionary items
foreach (KeyValuePair<string, Customer> item in itemsFetched)
{
    // Update Postal Code
    item.Value.PostalCode = "05023";

    // Create CacheItem of updated Customer object
    CacheItem updatedCacheItem = new CacheItem(item.Value);

    // Add CacheItem to dictionary
    itemsUpdated.Add(item.Key,updatedCacheItem);
}

if (UpdateDB(itemsUpdated))
{
    // Insert updated bulk items to Cache
    IDictionary<string, Exception> keysFailedToInsert = cache.InsertBulk(itemsUpdated);

    if (keysFailedToInsert.Count > 0)
    {
        foreach (KeyValuePair<string, Exception> keyFailedToInsert in keysFailedToInsert)
            Console.WriteLine($"Could not update Item {keyFailedToInsert.Key} in cache due to error : {keyFailedToInsert.Value}");
    }
}
// Precondition: Cache is already connected
// Create an array of all Customer Keys
List<String> keys = List.of(
        "Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
);

// Get items from cache
Map<String, Customer> itemsFetched = cache.getBulk(keys, Customer.class);

// Create a dictionary to store updated items
Map<String, CacheItem> itemsUpdated = new HashMap<>();

// Update postal codes of dictionary items
for (Map.Entry<String, Customer> item : itemsFetched.entrySet()) {
    // Update Postal Code
    item.getValue().setPostalCode("05023");

    // Create CacheItem of updated Customer object
    CacheItem updatedCacheItem = new CacheItem(item.getValue());

    // Add uCacheItem to dictionary
    itemsUpdated.put(item.getKey(), updatedCacheItem);
}

if (updateDB(itemsUpdated)) {
    // Insert updated bulk items to Cache
    Map<String, Exception> keysFailedToInsert = cache.insertBulk(itemsUpdated);

    if (keysFailedToInsert.size() > 0) {
        for (Map.Entry<String, Exception> keyFailedToInsert : keysFailedToInsert.entrySet()) {
            System.out.printf("Could not update Item %s in cache due to error : %s", keyFailedToInsert.getKey(), keyFailedToInsert.getValue());
        }
    }
}
# Precondition: Cache is already connected
# Fetch all products from database
products = fetch_products_from_db()

# Create map of items to be inserted to cache
dictionary = {}

for product in products:
    key = "Product:" + product.get_product_id()
    cache_item = ncache.CacheItem(product)

    # Add items to dictionary
    dictionary[key] = cache_item

keys_failed_to_insert = cache.insert_bulk(dictionary)

if len(keys_failed_to_insert) > 0:
    for entry in keys_failed_to_insert:
        if not keys_failed_to_insert[entry]:
            value = False
else:
    # Any other exception
    value = True
// Precondition: Cache is already connected
// Fetch all products from database
var products = await this.fetchProductFromDB();

// Create map of items to be added to cache
var dictionary = new Map();

products.forEach(prod => {
    var key = "Product:" + this.product.getProductID();
    var cacheItem = new ncache.CacheItem(this.product);

    // Insert dictionary to cache
    this.cache.insert(key,cacheItem);
});

var keysFailedToAdd = this.cache.addBulk(dictionary);

if(keysFailedToAdd.size() > 0)
{
    keysFailedToAdd.forEach(entry => {
        if(entry.getValue() == false)
        {
            var ex = false;
        }
        else
        {
            // Any other exception
        }
    });
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Create an array of all Customer Keys
String[] keys = new String[]
{
    "Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
};

// Create an array of all Customer Keys
IDictionary itemsFetched = cache.GetBulk(keys);

if (itemsFetched.Count < keys.Length)
{
    // Create a dictionary to store updated items
    IDictionary<string, CacheItem> missingItems = new Dictionary<string, CacheItem>();


    // Update dictionary items
    foreach (string key in keys)
    {
        if (!itemsFetched.Contains(key))
        {
            Customer customer = FetchCustomerFromDB(key);
            if (customer != null)
            {
                // Create CacheItem of updated Customer object
                CacheItem cacheItem = new CacheItem(customer);

                // Add CacheItem to dictionary
                missingItems.Add(key, cacheItem);
            }
        }
    }

    string[] missingKeys = new string[missingItems.Count];
    CacheItem[] missingCacheItems = new CacheItem[missingItems.Count];
    int index = 0;
    foreach (var keyValuePair in missingItems)
    {
        missingKeys[index] = keyValuePair.Key;
        missingCacheItems[index] = keyValuePair.Value;
        index++;
    }

    // Insert updated bulk items to Cache
    IDictionary keysFailedToAdd = cache.InsertBulk(missingKeys, missingCacheItems);

    if (keysFailedToAdd.Count > 0)
    {
        foreach (DictionaryEntry entry in keysFailedToAdd)
        {
            Console.WriteLine($"Could not add Item {entry.Key} in cache due to error: {entry.Value}");
        }
    }
}

Update Objects with Asynchronous API

InsertAsync returns the object of the Task class which can further be used according to the business needs of the client application.

  • .NET
  • Java
  • Python
  • Legacy API
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";

// Get customer from database if not found in cache
if (customer == null)
{
    Customer customer = FetchCustomerFromDB("ALFKI");
}

// Update customer's Phone
customer.Phone = "12345-6789";

// Update cutsomer in DB and Cache
if (UpdateDB(customer))
{
    // Adding item asynchronously.
    Task<CacheItemVersion> task = cache.InsertAsync(customerKey, customer);

    // This task object can be used as per your business needs
    if (task.IsCompleted)
    {
        // Get CacheItemVersion object from task result
        CacheItemVersion version = task.Result;
        Console.WriteLine($"Item {customer.CustomerID} has been updated with version {version.Version}.");
    }
}
// Precondition: Cache is already connected
String customerKey = "Customer:ALFKI";

// Get customer from database if not found in cache
if (customer == null)
Customer customer = fetchCustomerFromDB("Customer:ALFKI");

// Update customer's Phone
customer.setPhone("12345-6789");

// Update cutsomer in DB and Cache
if (updateDB(customer)) {
    // Adding item asynchronously.
    FutureTask<CacheItemVersion> task = cache.insertAsync(customerKey, customer);

    // Wait for task to complete and get CacheItemVersion object from task result
    CacheItemVersion version = task.get();
    System.out.println("Item " + customer.getCustomerID() + " has been updated with version " + version.getVersion() + ".");
}
# Precondition: Cache is already connected
# Get product from database
product = fetch_product_from_db()

# Generate a unique cache key for this product string
key = "Product:{product.get_product_id()}"

# Insert Product object to cache asynchronously
async def insert_async():
    task = cache. insert_async("key", "product")
    value = await task

asyncio.run(insert_async())

print("Item " + key + "has been updated.")
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);

CacheItem cacheItem = new CacheItem(customer);

if (customer == null)
{
    // Adding item asynchronously.You can also add data by creating a CacheItem object which stores meta data as well
    cache.InsertAsync(customerKey, cacheItem, DSWriteOption.None, null);
    Console.WriteLine($"Item {customer.CustomerID} has been updated.")
}

Additional Resources

NCache provides a sample application for Basic Operations on GitHub.

See Also

.NET: Alachisoft.NCache.Client namespace.
Java: com.alachisoft.ncache.client namespace.
Python: ncache.client class.
Node.js: Cache class.

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Community
  • 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