cache-aside
With the cache-aide pattern, application code uses the cache directly.
This means that application code which accesses the system-of-record (SOR) should consult the cache first, and if the cache contains the data, then return the data directly from the cache, bypassing the SOR.
Otherwise, the application code must fetch the data from the system-of-record, store the data in the cache, and then return it.
When data is written, the cache must be updated with the system-of-record. This results in code that often looks like the following pseudo-code:
public class MyDataAccessClass
{
private final Ehcache cache;
public MyDataAccessClass(Ehcache cache)
{
this.cache = cache;
}
/* read some data, check cache first, otherwise read from sor */
public V readSomeData(K key)
{
Element element;
if ((element = cache.get(key)) != null) {
return element.getValue();
}
// note here you should decide whether your cache
// will cache 'nulls' or not
if (value = readDataFromDataStore(key)) != null) {
cache.put(new Element(key, value));
}
return value;
}
/* write some data, write to sor, then update cache */
public void writeSomeData(K key, V value)
{
writeDataToDataStore(key, value);
cache.put(new Element(key, value);
}