CacheStore 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.CacheStore allows read-through and write-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.CacheStore is provided to ensure read-through and write-through behavior of the cache. Whenever an object is put into cache or removed from cache, a method on cache store is called to perform the operation in the secondary storage.

The CacheStore interface extends the CacheLoader interface to ensure read-through semantic.

The CacheStore is called in the following cases:

  • The store(Object key,Object value)} method is invoked when the {{IMap.put(Object key, Object value) is called.
  • The storeAll(Map) method is invoked when the IMap.putAll(Map collection) is called.
  • The remove(Object key) method is invoked when the IMap.remove(Object key) is called.
  • The removeAll(Collection keys) method is not supported.
The CacheStore 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.

Configuration

Cache store is configured via the space schema XML configuration file. Here are the tags required to setup CacheStore 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.cachestore.MyCacheStoreImpl</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>
You may define only one CacheLoader or CacheStore per space.

The CacheStore methods

Return Value Method
void erase(java.lang.Object key)
Remove the specified key from the underlying store if present.
void eraseAll(java.util.Collection keys)
Remove the specified keys from the underlying store if present
void store(java.lang.Object key, java.lang.Object value)
Store the specified values under the specified keys in the store.
void storeAll(java.util.Map map)
Store the specified values under the specified keys in the underlying store.

Example

The following example loads data from the database and stores it in the database. The example uses the Person class described below. The CacheStoreImpl.init method initializes the database connection. The CacheStoreImpl.store checks for the the relevant object needed to be updated or inserted into the database.

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.cachestore;
 
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.javax.cache.CacheStore;
import com.j_spaces.sadapter.GenericPA.*;
 
public class CacheStoreImpl implements CacheStore, CacheLifeCycleManager {
       String tableName = "Person";
 
       Connection dbConnection;
 
       public CacheStoreImpl() {
 
       }
 
       /**
        * @param dbUrl
        * @param user
        * @param password
        * @param properties
        */
       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);// + "
                    // tableName = properties.getProperty("TableName");
                    dbConnection = DriverManager.getConnection(dbURL, "sa", "");
                    System.out.println();
                    System.out.println(" ********* CACHE STORE STARTED ********* ");
                    System.out.println();
 
                    Statement st = dbConnection.createStatement();
 
                    try {
                           String dropSQL = "DROP TABLE " + tableName;
                           st.executeUpdate(dropSQL);
                    } catch (Exception e) {
                    }
                    // create table
                    String createSQL = "CREATE TABLE " + tableName
                                  + "(FirstName VARCHAR(3000) ,"
                                  + " LastName VARCHAR(3000) , ID INTEGER )";
 
                    System.out.println(createSQL);
                    st.executeUpdate(createSQL);
                    System.out.println(createSQL + " OK!");
                    st.executeUpdate("CREATE INDEX FirstNameIndex ON Person (FirstName)");
                    st.executeUpdate("CREATE INDEX LastNameIndex ON Person (LastName)");
                    st.executeUpdate("CREATE INDEX IDIndex ON Person (ID)");
                    System.out.println("Index creation OK!");
 
              } catch (Exception e) {
                    e.printStackTrace();
              }
 
       }
 
       /**
        * @param key
        * @return value
        */
       public Object load(Object key) {
 
              Object values[] = null;
              Person person = null;
              try {
                    PreparedStatement stP = dbConnection
                                  .prepareStatement("select * from  " + this.tableName
                                                + " where ID = ? ");
                    stP.setInt(1, Integer.valueOf(key.toString()).intValue());
 
                    ResultSet rs = stP.executeQuery();
                    int sz = rs.getMetaData().getColumnCount();
                    // System.out.println("Cols: " + sz );
 
                    values = new Object[sz];
                    while (rs.next()) {
                           for (int i = 0; i < sz; i++) {
                                  values[i] = rs.getObject(i + 1);
                                  // System.out.println("--->>>>>>>>>>>>Got cell data:" +
                                  // values[i]);
                           }
                           // 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) {
              HashMap msgMap = new HashMap();
              if (keys != null) {
                    Iterator iter = keys.iterator();
                    while (iter.hasNext()) {
                           Object key = iter.next();
                           msgMap.put(key, load(key));
                    }
              }
 
              else {
                    try {
                           PreparedStatement stP = dbConnection
                                         .prepareStatement("select * from  "
                                                       + this.tableName);
                          
                           ResultSet rs = stP.executeQuery();
                           while (rs.next()) {
                                  Integer key = new Integer(rs.getInt(3));
                                  Person person = new Person(rs.getString(1), rs.getString(2), key);
                                 
                                  msgMap.put(key, person);
                           }
                           rs.close();
                    } catch (Exception e) {
                           e.printStackTrace();
                    }
              }
 
              return msgMap;
       }
 
       /**
        * @param key
        */
       public void erase(Object key) {
              PreparedStatement stPd;
              try {
                    stPd = dbConnection.prepareStatement("delete from "
                                  + this.tableName + " where ID = ? ");
                    int value = Integer.parseInt((String) key);
                    stPd.setInt(1, value);
                    stPd.executeUpdate();
                    stPd.close();
              } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
              }
       }
 
       public void store(Object key, Object value) {
              PreparedStatement stPd;
              try {
                    if (value instanceof Person) {
                           // check if we need to perform update or insert
                           stPd = dbConnection.prepareStatement("select ID from "
                                         + this.tableName + " where ID = ? ");
 
                           int keyValue = Integer.parseInt(key.toString());
                           stPd.setInt(1, keyValue);
 
                           ResultSet rs = stPd.executeQuery();
                           Person obj = (Person) value;
 
                           if (rs.next()) {
                                  // System.out.println("Update "+obj );
                                  stPd.close();
                                  stPd = dbConnection.prepareStatement("update "
                                                + this.tableName
                                                + " set FirstName =?  where  LastName =? ");
                                  stPd.setString(1, obj.firstName);
                                  stPd.setString(2, obj.lastName);
                                  stPd.executeUpdate();
                                  stPd.close();
                           } else {
                                  // System.out.println("Insert " +obj );
                                  stPd.close();
                                  stPd = dbConnection.prepareStatement("insert into "
                                                + this.tableName
                                                + " (FirstName, LastName, ID) values(?,?,?) ");
                                  stPd.setString(1, obj.firstName);
                                  stPd.setString(2, obj.lastName);
                                  stPd.setInt(3, obj.id);
                                  stPd.executeUpdate();
                                  stPd.close();
                           }
                    }
              } catch (Exception e) {
                    e.printStackTrace();
              }
       }
 
       /**
        * @param map
        */
       public void storeAll(Map map) {
 
              Iterator keyIter = map.keySet().iterator();
 
              while (keyIter.hasNext()) {
                    Object key = keyIter.next();
                    store(key, map.get(key));
              }
       }
 
       public void shutdown() {
       };
 
       public void eraseAll(Collection keys) {
       };
 
       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)