Alachisoft NCache 4.1 - Online Documentation

Access Multiple Caches in Single Application

 
Multiple caches can be initialized in a single application; there is no limit for number of caches in one application. Following is an example using multiple caches:
 
  1. Include the following import statements in your project:
     
    import com.alachisoft.ncache.web.caching.*;
     
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
     
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    ....
    }
     
  4. Now insert the following code in the 'Main' of the project.
     
    Cache _cache1 = NCache.initializeCache("myCache");
    Cache _cache2 = NCache.initializeCache("myReplicatedCache");
     
    // Perform any of the operations provided by NCache on any of the cache initialized
    _cache1.clear();
    _cache2.clear();
     
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
     
    Customer customer1 = new Customer();
    customer1.name = "Alex";
    customer1.customerID = 1002;
    customer1.setCity("Chicago");
    customer1.setContactNumber("+44-xxx-xxxx-xxxx");
    customer1.setOrderInProcess(false);
     
    // Add Item to Cache
    NCache.getCaches().getCache("myCache").add("Customer:David:1001", customer);
    NCache.getCaches().getCache("myReplicatedCache").add("Customer:Alex:1002", customer1);
       
    // Get Items from Cache
    Object object_Customer = NCache.getCaches().getCache("myCache").get("Customer:David:1001");
     
    Object object_Customer1 = NCache.getCaches().getCache("myReplicatedCache").add("Customer:Alex:1002");
     
    Customer customerInformation = (Customer)object_Customer;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
     
    System.out.println();
     
    customerInformation = (Customer)object_Customer1;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
     
  5. Start both the caches.
  6. Run the project.
 
 
See Also
 
Copyright © 2005-2012 Alachisoft. All rights reserved.