• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
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.

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, 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.
  • 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.

Retrieve Cache Data

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)

# Retrieve the Customer object
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);

// Retrieve the Customer object
var retrievedItem = await this.cache.get(key, Product);

if (retrievedItem != null)
{
    // Perform your logic
}
else
{
    // Null returned; no key exists
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);

// Retrieve the Customer object
object result = cache.Get(customerKey);

if (result != null)
{
    Console.WriteLine($"Customer: {customer.ContactName}, Address : {customer.Address}");
}
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

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
// Precondition: Cache is already connected
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}");
}
// Precondition: Cache is already connected
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());
}
# Precondition: Cache is already connected
# 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")
// Precondition: Cache is already connected
// 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
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";

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

if (retrievedCacheItem != null)
{
    Customer customer = (Customer)retrievedCacheItem.Value;
    Console.WriteLine($"Customer: {customer.ContactName}, Address : {customer.Address}");
}

Retrieve Bulk Items From Cache

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 any existing CacheItem that contains an object 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
// Precondition: Cache is already connected
// 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}");
}
// Precondition: Cache is already connected
// 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());
}
# Precondition: Cache is already connected
# 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")
// Precondition: Cache is already connected
// 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
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// 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 retrievedItems = cache.GetBulk(keys);

// Retrieve customers and their addresses from dictionary
foreach (DictionaryEntry entry in retrievedItems)
{
    string key = (string)entry.Key;
    Customer customer = (Customer)entry.Value;

    Console.WriteLine($"Customer: {customer.ContactName}, Address: {customer.Region}");
}

Retrieve CacheItem Bulk From Cache

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

  • .NET
  • Java
  • Python
  • Node.js
// Precondition: Cache is already connected
// 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}");
}
// Precondition: Cache is already connected
// 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
        }
    }
}
# Precondition: Cache is already connected
# 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")
// Precondition: Cache is already connected
// 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.

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