• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
Show / Hide Table of Contents

Retrieve Existing Cache Data

While NCache also supports querying the cache data, it utilizes the key-value architecture of its store to maximize the ways of data retrieval. You can retrieve a custom object, CacheItem, or bulk items from the cache using the unique key associated with the item. NCache provides various overloads of the Get method to fetch items from the cache data based on the specified key.

Prerequisites to Retrieve Existing Cache Data

  • .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, CacheItem, GetCacheItem, Get, GetList, GetBulk, GetCacheItemBulk.
  • 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, getCacheItem, get, getList, getBulk.
  • 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, get, get_cacheitem, get_bulk.
  • 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, getCacheItem, get, getList, getBulk.
  • 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.

Retrieve Cache Data

Note

This feature is also available in NCache Professional.

You can fetch a custom object from the cache data using various overloads of the Get method by specifying the key of the cache item. The object is retrieved as a template, so it needs to be type-cast accordingly if it is a custom class object.

Important

If the key does not exist in the cache, a null value is returned.

The following example fetches an existing item of the Customer class with the specified key. Keep in mind that Get returns a template that needs to be cast accordingly, so the object is cast to the Customer type in this example.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected

string customerKey = "Customer:ALFKI";

// Retrieve the Customer object
Customer customer = cache.Get<Customer>(customerKey);

if (customer != null)
{
    Console.WriteLine($"Customer: {customer.ContactName}, Address : {customer.Address}");
}
// Precondition: Cache is already connected

String customerKey = "ALFKI";

// Retrieve the Customer object

Customer customer =  cache.get(customerKey, Customer.class);
System.out.println("Customer with key " + customerKey + " has value " + customer);
# Precondition: Cache is already connected

# Get Product from database against given ProductID
product = fetch_product_from_db()

# Get key to fetch from cache
key = "Product:" + product.get_product_id()

# Create a CacheItem
cache_item = ncache.CacheItem(product)

cache.insert(key, cache_item)

# Get item against key from cache in given Class type
retrieved_item = cache.get(key, Product)

if retrieved_item is not None:
    # Perform your logic
    print("Item received")
else:
    # Null returned; no key exists
    print("Key does not exist")
// Precondition: Cache is already connected
// This is an async method

// Get Product from database against given ProductID
var product = this.fetchProductFromDB(1001);

// Get key to fetch from cache
var key = "Product:" + this.product.getProductID();

// Create a CacheItem
var cacheItem = new ncache.CacheItem(product);

await this.cache.insert(key , cacheItem);

// Get item against key from cache in given Class type
var retrievedItem = await this.cache.get(key, Product);

if (retrievedItem != null)
{
    // Perform your logic
}
else
{
    // Null returned; no key exists
}
string key = "Product:1001";
Product product = null;
//null is returned if key does not exist in the cache.
object result = cache.Get(key);
if (result != null)
{
    if (result is Product)
    {
    product = (Product)result;
    }
}
Note

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

Retrieve CacheItem From Cache

Note

This feature is also available in NCache Professional.

NCache allows retrieving an existing CacheItem from the cache using the dedicated GetCacheItem API. This returns a CacheItem associated with the specified key. Its Value property encapsulates the data.

The following example retrieves an existing CacheItem with specified key and checks if the result is of Customer type and type casts it accordingly.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
string customerKey = "Customer:ALFKI";

// Retrieve the CacheItem
CacheItem retrievedCacheItem = cache.GetCacheItem(customerKey);

if (retrievedCacheItem != null)
{
    Customer customer = retrievedCacheItem.GetValue<Customer>();
    Console.WriteLine($"Customer: {customer.ContactName}, Address : {customer.Address}");
}
String customerKey = "ALFKI";

// Retrieve the CacheItem from cache
CacheItem retrievedCacheItem = cache.getCacheItem(customerKey);

if (retrievedCacheItem != null) {
    // Get the Customer object from the CacheItem
    Customer customer = retrievedCacheItem.getValue(Customer.class);
    System.out.println("Customer: " + customer.getContactName() + ", Phone: " + customer.getPhone());
}
# Generate key to fetch from cache
key = "Product:1001"

# Get CacheItem from cache
retrieved_cache_item = cache.get_cacheitem(key)

# Get item against key from cache in given Class type

if retrieved_cache_item is not None:
    value = retrieved_cache_item.get_value(Product)
    # Perform your logic
else:
    # Null returned no key exists
    print("Key does not exist")
// This is an async method
// Get key to fetch from cache
var key = "Product:" + this.product.getProductID();

// Get CacheItem from cache
var retrievedCacheItem = this.cache.getCacheItem(key);

// Get item against key from cache in given Class type

if (retrievedCacheItem != null)
{
    this.cache.getValue(Product);
    // Perform your logic
}
else
{
    // Null returned; no key exists
}
string key = "Product:1001";
Product product = null;
CacheItem result = cache.GetCacheItem(key);
if (result != null)
{
    if (result.Value is Product){
    product = (Product)result.Value;
    }
}

Retrieve Bulk Items From Cache

Note

This feature is also available in NCache Professional.

NCache allows synchronous bulk retrieval of items in a single call to reduce network costs. Various overloads of the GetBulk method retrieve objects from the cache data for the cache keys specified. Note that the value is retrieved as a template so it needs to be type cast accordingly if it is a custom class object.

Important

If the keys exist in the cache, a dictionary of cache items and their keys is returned.

The following example retrieves existing CacheItems containing objects of the Customer class. The result is returned in an IDictionary of keys and values, which can be enumerated to get the actual values of the keys. Since GetBulk returns a template (that needs to be cast), the object is cast to the Customer type in this example. If the specified key does not exist in the cache, a null value is returned.

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

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

// Retrieve customers and their addresses from dictionary
foreach (KeyValuePair<string, Customer> retrievedItem in retrievedItems)
{
    Console.WriteLine($"Customer: {retrievedItem.Value.ContactName}, Address : { retrievedItem.Value.Address}");
}
// Create an list of all keys to fetch
List<String> keys = List.of(
        "Customer:ALFKI",
        "Customer:ANATR",
        "Customer:ANTON",
        "Customer:AROUT",
        "Customer:BERGS"
);

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

// Retrieve customers and their addresses from dictionary
for (Map.Entry<String, Customer> retrievedItem : retrievedItems.entrySet())
{
    System.out.println("Customer: " + retrievedItem.getValue().getContactName() + ", Address: " + retrievedItem.getValue().getAddress());
}
# Get Products from database
products = fetch_products_from_db()

# Get keys to fetch from cache
keys = []
index = 0

for product in products:
    keys.append( "Product:" + product.get_product_id())

# Get bulk from cache
retrieved_items = cache.get_bulk(keys, Product)

# Check if any keys have failed to be retrieved
if len(retrieved_items) is len(keys):
    # Perform operations according to business logic
    print("All the items were retrieved successfully")
else:
    # Not all the keys are present in cache
    print("Some of the keys were not found")
// This is an async method
// Get Product from database against given ProductID
var products = await this.fetchProductFromDB();

// Get keys to fetch from cache
var keys = [products.length];
var index = 0;

products.forEach(product => {

    keys[index] ="Product:" + this.product.getProductID();
    index++;

});

// Get bulk from cache
var retrievedItems = await this.cache.getBulk(keys,Product);

// Check if any keys have failed to be retrieved
if(retrievedItems.size() == keys.length)
{
    retrievedItems.forEach(entry => {

        if(entry.getValue() instanceof Product)
        {
            // Perform operations according to business logic
        }
        else
        {
            // Object not of Product type
        }
    });
}
else
{
    // Not all of the keys are present in cache
}
string[] keys = { "Product:1001", "Product:1002" };

IDictionary items = cache.GetBulk(keys);

if (items.Count > 0){
    IEnumerator iter = items.Values.GetEnumerator();
while (iter.MoveNext()){
        Product info = (Product)iter.Current;
        //do something
    }
}

Retrieve Bulk of CacheItem's From Cache

Note

This feature is also available in NCache Professional.

You can also retrieve a bulk of CacheItem using the GetCacheItemBulk method. Here is an example:

  • .NET
  • Java
  • Python
  • Node.js
// Create an array of all keys to fetch
String[] keys = new String[]
{
    "Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT",
    "Customer:BERGS"
};

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

// Retrieve customers and their addresses from dictionary
foreach (KeyValuePair<string, Customer> retrievedItem in retrievedItems)
{
    Console.WriteLine($"Customer: {retrievedItem.Value.ContactName}, Address : { retrievedItem.Value.Address}");
}
// Fetch a products array
Product[] products = fetchProducts();

// Get keys to fetch from cache
ArrayList<String> keys = new ArrayList<>(products.length);

for (Product product : products)
{
    String key = "Product:" + product.getProductID();
    keys.add(key);
    cache.insert(key , product);
}

// Retrieve items from cache in a Map
java.util.Map<String, CacheItem> retrievedItems = cache.getCacheItemBulk(keys);

// Check if any keys have failed to be retrieved
if (retrievedItems.size() == keys.size())
{
    for (java.util.Map.Entry<String, CacheItem> entry : retrievedItems.entrySet())
    {
        if (entry.getValue() != null)
        {
            Product prod = entry.getValue().<Product>getValue(Product.class);

            // Perform operations according to business logic
        }
        else
        {
            // Object not of Product type
        }
    }
}
else
{
    // Not all of the keys are present in cache
    for (String key : keys)
    {
        if (!retrievedItems.containsKey(key))
        {
            // This key does not exist in cache
        }
    }
}
# Get Products from database
products = fetch_products_from_db()

# Get keys to fetch from cache
keys = []
index = 0

for product in products:
    keys.append( "Product:" + product.get_product_id())

# Get bulk from cache
retrieved_items = cache.get_cacheitem_bulk(keys)

# Check if any keys have failed to be retrieved
if len(retrieved_items) is len(keys):
    for item in retrieved_items:
        product = retrieved_items[item].get_value(Product)
        # Perform operations according to business logic
else:
    # Not all the keys are present in cache
    print("Some of the keys were not found")
// This is an async method
// Get Product from database against given ProductID
var products = await this.fetchProductFromDB();

// Get keys to fetch from cache
var keys = [products.length];
var index = 0;

products.forEach(product => {
    keys[index] ="Product:" + this.product.getProductID();
    index++;
});

// Get bulk from cache
var retrievedItems = this.cache.getCacheItemBulk(keys);

// Check if any keys have failed to be retrieved
if(retrievedItems.size() == keys.length)
{
    retrievedItems.forEach(entry => {
        if(entry.getValue() instanceof ncache.CacheItem)
        {
            var prod = entry.getValue();

            // Perform operations according to business logic
        }
        else
        {
            // Object not of Product type
        }
    });
}
else
{
    // Not all of the keys are present in cache

    keys.forEach(key => {

        if(retrievedItems.containsKey(key) == false)
        {
            //  key does not exist in cache
        }
    });
}

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.

In This Article
  • Prerequisites to Retrieve Existing Cache Data
  • Retrieve Cache Data
    • Retrieve CacheItem From Cache
  • Retrieve Bulk Items From Cache
  • Retrieve Bulk of CacheItem's From Cache
  • Additional Resources
  • See Also

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 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top