CacheLoader Interface - 5.0

  GigaSpaces 5.X

Documentation Home
Quick Start Guide
Release Notes

Previous release

  Search Here
Searching GigaSpaces Platform 5.X Documentation

                                               

Summary: The com.j_spaces.javax.cache.CacheLoader interface allows read-through behavior of the cache.

This page is specific to:
GigaSpaces 5.x

This feature is deprecated as of version 6.0

Overview

The com.j_spaces.javax.cache.CacheLoader interface is provided to ensure read-through behavior of the cache. Whenever an object is not in the space cache, the cache loader is used to transparently load the object from a secondary storage to the user.

The CacheLoader interface as it is described in this section is relevant only if you are using GigaSpaces 5.0 and earlier versions. If you are using GigaSpaces 5.1 and onwards, refer to the Read-Through and Write-Through section.

The CacheLoader is called in the following cases:

  • The load(Object key) method is invoked whenever a cache miss occurs during calls to the IMap.get(Object key).
  • The loadAll(Collection keys) method is called when calling the IMap.getAll(Collection keys) with a null keys parameter. IMap.getAll(Collection keys) with non null keys calls the load(Object key).

    Configuration

    A cache loader is configured via the space schema XML configuration file. Here are the tags required to setup CacheLoader implementation:

    <engine>
    <!--default cache size of Cache Manager-->
           <cache_size>5000000</cache_size>
           <!--0 - LRU POLICY, 1 - ALL IN CACHE , default value: 1 -->
           <cache_policy>0</cache_policy>
    </engine>
     
    <persistent>
    <enabled>true</enabled>
    <!-- name of the storage adapter class to be used by the space -->
    <StorageAdapterClass>com.j_spaces.sadapter.GenericPA.GenericPersistentAdapter</StorageAdapterClass>
    <AdapterType>com.j_spaces.sadapter.GenericPA.CustomPesistentCache</AdapterType>
    <!-- CacheLoader or CacheStore implementation class name that will be used by space -->
    <CacheLoaderClass>com.example.cacheLoader.MyCacheLoaderImpl</CacheLoaderClass>
    <DataBaseName>jdbc:hsqldb:testDB</DataBaseName>
    <userName>sa</userName>
    <password></password>
           <!-- path to the directory that holds the database properties and data type mapping
    e.g ${com.gs.home}/GenericPersistProperties -->
    <StorageAdapterURL>${com.gs.home}/GenericPersistProperties</StorageAdapterURL>
    <!-- if true persistent space will be forced to start in COLD_INIT(empty) otherwise WARM_INIT -->
    <force-cold-init>false</force-cold-init>
    </persistent>
     
    <filters>
    <filter-names>CacheLoader-Filter</filter-names>
           <CacheLoader-Filter>
                        <enabled>true</enabled>
                   <security>false</security>
                   <class>com.example.cacheLoader.MyCacheLoaderImpl</class>
                   <url>none</url>
                   <priority>1</priority>
                   <!-- 51 - On init;-->
                   <operation-code>51</operation-code>
    </CacheLoader-Filter>
    </filters>

CacheLoader methods

Return value Method
java.lang.Object load (java.lang.Object key)
Loads value from secondary data storage in case it's not in the cache.
java.util.Map loadAll (java.util.Collection keys)
Loads multiple values from secondary data storage in case they are not in the cache.

Example

The following example demonstrates a CacheLoader implementation. The CacheLoaderImpl class loads data from the database into the Person class. The CacheLifeCycleManager.init() is used to initialize the database connection. The ISpaceFilter.init method is used to load data from the database when the space is started.

package com.j_spaces.examples.cachestore;
 
import java.io.Serializable;
 
public class Person  implements Serializable  {
       public String firstName;
       public String lastName;
       public Integer id;
 
       // must have empty constructor
       public Person() {
       }
 
       public Person(String firstName, String lastName, Integer id) {
              this.firstName = firstName;
              this.lastName = lastName;
              this.id = id;
       }
 
       public String toString ()
       {
       return "ID:" +id +   " firstName:"+firstName + " lastName:"+lastName;
       }
}
package com.j_spaces.examples.cacheloader;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
 
import com.j_spaces.core.client.ClientUIDHandler;
import com.j_spaces.javax.cache.Cache;
import com.j_spaces.javax.cache.CacheLifeCycleManager;
import com.j_spaces.javax.cache.CacheLoader;
import com.j_spaces.sadapter.GenericPA.*;
 
public class CacheLoaderImpl  implements
              CacheLoader, CacheLifeCycleManager, ISpaceFilter{
       String tableName = "Person";
       IMap          cache;
       IJSpace              space;
       Connection dbConnection;
 
       public CacheLoaderImpl() {
 
       }
 
// ISpaceFilter init - Called after the CacheLoader init method
public void init(IJSpace space, String filterId, String url,int priority)
  {
              this.space = space;
  }
 
// ISpaceFilter process
public Object  process(SpaceContext context, ISpaceFilterEntry entry, int operationCode)       {
          if( operationCode == FilterOperationCodes.ON_INIT)
          {
              System.out.println("\nCalling CacheLoader Init >>>> ["+operationCode +"]\n");
              if (this.cache == null)
                     this.cache = new GSMapImpl(space);
                    
              Vector keyVec = new Vector();    
              keyVec.add( new Integer(1002));
              keyVec.add( new Integer(1003));
              keyVec.add( new Integer(1004));
 
              try {
              cache.getAll(keyVec);
 
                } catch (CacheException e) {
                     e.printStackTrace();
                }
              System.out.println("\nCacheLoader Init completed>>>>\n");
    }
              return null;
       }
       /**
        * @param dbUrl
        * @param user
        * @param password
        * @param properties
        *
        * @return database connection
        */
       public void init(String dbUrl, String user,
                    String password, Properties properties) {
              try {
                    Class.forName("org.hsqldb.jdbcDriver").newInstance();
                    System.out.println("Connection to HSQL database - URL:" + dbUrl);
                    dbConnection = DriverManager.getConnection(dbUrl, "sa", "");
                    System.out.println();
                    System.out.println(" ********* CACHE LOADER STARTED ********* ");
                    System.out.println();
              } catch (Exception e) {
                    e.printStackTrace();
              }
       }
 
       /**
        * @param key
        * @return value
        */
       public Object load(Object key) {
 
              Object values[] = null;
              Person person = null;
 
              /*
               * This is where a call to the external data source needs to be made and
               * load the data to the cache from an external data source. The
               * application performs a call to the appropriate database table, reads
        * the data using an appropriate query and fills in the relevant object
               */
              try {
 
                    PreparedStatement stP = dbConnection
                                  .prepareStatement("select * from  " + this.tableName
                                                + " where ID = ? ");
                    ResultSet rs = stP.executeQuery();
                    int sz = rs.getMetaData().getColumnCount();
                   
                    while (rs.next()) {
                           for (int i = 0; i < sz; i++) {
                                  values[i] = rs.getObject(i + 1);
                           }
                           // HERE WE MAP table row to Person object
                           person = new Person(String.valueOf(values[0]), String.valueOf(values[1]) ,
                            Integer.valueOf(String.valueOf(values[2])));
                           break;
                    }
              } catch (Exception e) {
                    e.printStackTrace();
              }
              //System.out.println("return:" + person);
              return person;
       }
 
       /**
        * @param keys
        * @return collection of values
        */
       public Map loadAll(Collection keys) {
              Iterator iter = keys.iterator();
              HashMap msgMap = new HashMap();
              while (iter.hasNext()) {
                    msgMap.put(keys, load(iter.next()));
              }
              return msgMap;
       }
 
       public void shutdown() {
       }
 
       public void eraseAll() {
       }
}

Wiki Content Tree


Your Feedback Needed!

We need your help to improve this wiki site. If you have any suggestions or corrections, write to us at techw@gigaspaces.com. Please provide a link to the wiki page you are referring to.

Labels

 
(None)