There are several common access patterns when using a cache. Ehcache supports the following patterns:

  • Cache-aside (or direct manipulation)
  • Cache-as-sor (a combination of read-through and write-through or write-behind patterns)
  • Read-through
  • Write-through
  • Write-behind (or write-back)
  • Copy cache

cache-aside

With the cache-aside 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 (V) 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));
} }

cache-as-sor

The cache-as-sor pattern implies using the cache as though it were the primary system-of-record (SOR). The pattern delegates SOR reading and writing activities to the cache, so that application code is absolved of this responsibility.

To implement the cache-as-sor pattern, use a combination of the following read and write patterns:

  • read-through
  • write-through or write-behind

Advantages of using the cache-as-sor pattern are:

  • Less cluttered application code (improved maintainability)
  • Choice of write-through or write-behind strategies on a per-cache basis (use only configuration)
  • Allows the cache to solve the "thundering-herd" problem

A disadvantage of using the cache-as-sor pattern is:

  • Less directly visible code-path
public class MyDataAccessClass { 

    private final Ehcache cache; 

    public MyDataAccessClass(Ehcache cache) {
cache.registerCacheWriter(new MyCacheWriter());
this.cache = new SelfPopulatingCache(cache);
} /* read some data - notice the cache is treated as an SOR.
* the application code simply assumes the key will always be available
*/
public V readSomeData(K key) {
return cache.get(key);
} /* write some data - notice the cache is treated as an SOR, it is
* the cache's responsibility to write the data to the SOR.
*/
public void writeSomeData(K key, V value) {
cache.put(new Element(key, value);
}
} /**
* Implement the CacheEntryFactory that allows the cache to provide the
* read-through strategy
*/
private class MyCacheEntryFactory implements CacheEntryFactory {
public Object createEntry(Object key) throws Exception {
return readDataFromDataStore(key);
}
} /**
* Implement the CacheWriter interface which allows the cache to provide the
* write-through or write-behind strategy.
*/
private class MyCacheWriter implements CacheWriter {
public CacheWriter clone(Ehcache cache) throws CloneNotSupportedException {
throw new CloneNotSupportedException();
} public void init() { } void dispose() throws CacheException { } void write(Element element) throws CacheException {
writeDataToDataStore(element.getKey(), element.getValue());
} void writeAll(Collection<Element> elements) throws CacheException {
for (Element element : elements) {
write(element);
}
} void delete(CacheEntry entry) throws CacheException {
deleteDataFromDataStore(element.getKey());
} void deleteAll(Collection<CacheEntry> entries) throws CacheException {
for (Element element : elements) {
delete(element);
}
}
}

read-through

The read-through pattern mimics the structure of the cache-aside pattern when reading data. The difference is that you must implement the CacheEntryFactory interface to instruct the cache how to read objects on a cache miss, and you must wrap the Cache instance with an instance of SelfPopulatingCache.

write-through

The write-through pattern mimics the structure of the cache-aside pattern when writing data. The difference is that you must implement the CacheWriter interface and configure the cache for write-through mode.

A write-through cache writes data to the system-of-record in the same thread of execution. Therefore, in the common scenario of using a database transaction in context of the thread, the write to the database is covered by the transaction in scope. For more details (including configuration settings) about using the write-through pattern, see Write-Through and Write-Behind Caches.

write-behind

The write-behind pattern changes the timing of the write to the system-of-record. Rather than writing to the system-of-record in the same thread of execution, write-behind queues the data for write at a later time.

The consequences of the change from write-through to write-behind are that the data write using write-behind will occur outside of the scope of the transaction.

This often-times means that a new transaction must be created to commit the data to the system-of-record. That transaction is separate from the main transaction. For more details (including configuration settings) about using the write-behind pattern, see Write-Through and Write-Behind Caches.

Copy Cache

A copy cache can have two behaviors: it can copy Element instances it returns, when copyOnRead is true and copy elements it stores, when copyOnWrite to true.

A copy-on-read cache can be useful when you can't let multiple threads access the same Element instance (and the value it holds) concurrently. For example, where the programming model doesn't allow it, or you want to isolate changes done concurrently from each other.

Copy on write also lets you determine exactly what goes in the cache and when (i.e., when the value that will be in the cache will be in state it was when it actually was put in cache). All mutations to the value, or the element, after the put operation will not be reflected in the cache.

A concrete example of a copy cache is a Cache configured for XA. It will always be configured copyOnRead and copyOnWrite to provide proper transaction isolation and clear transaction boundaries (the state the objects are in at commit time is the state making it into the cache). By default, the copy operation will be performed using standard Java object serialization. For some applications, however, this might not be good (or fast) enough. You can configure your own CopyStrategy, which will be used to perform these copy operations. For example, you could easily implement use cloning rather than Serialization.

For more information about copy caches, see “Passing Copies Instead of References” in the Configuration Guide for Ehcache.

Ehcache(2.9.x) - API Developer Guide, Cache Usage Patterns的更多相关文章

  1. Ehcache(2.9.x) - API Developer Guide, Cache Loaders

    About Cache Loaders A CacheLoader is an interface that specifies load() and loadAll() methods with a ...

  2. Ehcache(2.9.x) - API Developer Guide, Cache Decorators

    About Cache Decorators Ehcache uses the Ehcache interface, of which Cache is an implementation. It i ...

  3. Ehcache(2.9.x) - API Developer Guide, Cache Eviction Algorithms

    About Cache Eviction Algorithms A cache eviction algorithm is a way of deciding which element to evi ...

  4. Ehcache(2.9.x) - API Developer Guide, Cache Manager Event Listeners

    About CacheManager Event Listeners CacheManager event listeners allow implementers to register callb ...

  5. Ehcache(2.9.x) - API Developer Guide, Cache Event Listeners

    About Cache Event Listeners Cache listeners allow implementers to register callback methods that wil ...

  6. Ehcache(2.9.x) - API Developer Guide, Cache Exception Handlers

    About Exception Handlers By default, most cache operations will propagate a runtime CacheException o ...

  7. Ehcache(2.9.x) - API Developer Guide, Cache Extensions

    About Cache Extensions Cache extensions are a general-purpose mechanism to allow generic extensions ...

  8. Ehcache(2.9.x) - API Developer Guide, Write-Through and Write-Behind Caches

    About Write-Through and Write-Behind Caches Write-through caching is a caching pattern where writes ...

  9. Ehcache(2.9.x) - API Developer Guide, Transaction Support

    About Transaction Support Transactions are supported in versions of Ehcache 2.0 and higher. The 2.3. ...

随机推荐

  1. 深入学习APC

    一.前言 在NT中,有两种类型的APCs:用户模式和内核模式.用户APCs运行在用户模式下目标线程当前上下文中,并且需要从目标线程得到许可来运行.特别是,用户模式的APCs需要目标线程处在alerta ...

  2. 【转】Android真机抓屏- Android Screen Monitor

    http://www.cnblogs.com/xiaofeixiang/p/4086092.html 一般运行Android应用程序有两种方式一种是设置Android虚拟设备模拟器,通过Android ...

  3. 节点文件将两个不同格式的XML文件,进行节点对照,并生成一个用于对照功能的XML

    本文纯属个人见解,是对前面学习的总结,如有描述不正确的地方还请高手指正~ 经常有的需求是,需要将一种格式的XML转换成另一种XML.如果要实现这个功能首先需要将两个不同XML手动建立节点对比关系.然后 ...

  4. Swift学习笔记三

    协议和扩展 在Objective-C中,协议是很常见也非常重要的一个特性,Swift中也保留了协议,语法略有变化. 用protocol关键字声明一个协议: protocol ExampleProtoc ...

  5. cdoj 1256 昊昊爱运动 预处理/前缀和

    昊昊爱运动 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/problem/show/1256 Descr ...

  6. Codeforces Gym 100203G G - Good elements 暴力

    G - Good elementsTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vjudge/contest/ ...

  7. w3cmark前端精彩博文周报 10.27-11.2

    w3cmark 官方Q群 145423956 | 官方微博 @w3cmark 这周周报来迟了,公司真的好忙!!!欢迎关注我们的微博 @w3cmark w3cmark推出每周精选前端博文推荐,通过阅读别 ...

  8. delphi label1 文字在窗体上水平来回移动

    //文字在窗体上水平来回移动 procedure TForm1.Timer1Timer(Sender: TObject);{ Timer1.Interval:=10;}begin  if label1 ...

  9. swift3.0 中NSNotification 的使用

    swift3.0 有很大变化,其中之一就是NSNotification使用跟原来不一样,以前NSNotification name是String:3.0中定义了一个类型NSNotification.n ...

  10. C++指针和引用

     ★ 相同点: 1. 都是地址的概念: 指针指向一块内存,它的内容是所指内存的地址:引用是某块内存的别名.  ★ 区别: 1. 指针是一个实体,而引用仅是个别名: 2. 引用使用时无需解引用(*),指 ...