воскресенье, 3 марта 2013 г.

Ehcache Usage Patterns

cache-aside (прямая манипуляция) - у нас обьект кеширования находится в объекте предоставляющем System Of a Record, и в методе возвращающем значение, мы сначала проверяем в кеше есть ли значение под переданный ключ и  случае успеха возвращаем его. В записи мы записываем как в кеш так и в SOR,
cache-as-sor (комбинация read-through и write-through или write-behind)
read-through - работа ведется с объектом кеша, только вот нам нужно создать для него реализацию CacheEntryFactory, которая подскажет как и откуда считать значение если произошел кеш-мис.
write-through - работа ведется через объект кеша, нужно реализовать CacheWriter. Запись в SOR происходит в том же потоке.
write-behind (or write-back) - почти все тоже что и предыдущий пункт, но запись в кеш происходит в отдельном потоке через очередь.

Cache-aside example


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);
  }
}

cache-as-sor example

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 elements) throws CacheException
   {
       for (Element element : elements) {
           write(element);
       }
   }
    void delete(CacheEntry entry) throws CacheException
   {
       deleteDataFromDataStore(element.getKey());
   }
    void deleteAll(Collection entries) throws CacheException
   {
       for (Element element : elements) {
           delete(element);
       }
   }
}
}

Комментариев нет:

Отправить комментарий