`

ehcache 缓存监听器的使用CacheEventListener

阅读更多

ehcache通过配置,可以实现诸如,内容最长缓存时间,内容最长没有被访问时间等功能,当以上时间expired,缓存中的内容将清空。

ehcache 缓存策略:
read-only:无需修改, 那么就可以对其进行只读 缓存,注意,在此策略下,如果直接修改数据库,即使能够看到前台显示效果,
但是将对象修改至cache中会报error,cache不会发生作用。另:删除记录会报错,因为不能在read-only模式的对象从cache中删除。
read-write:需要更新数据,那么使用读/写缓存 比较合适,前提:数据库不可以为serializable transaction isolation level
(序列化事务隔离级别)
nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,
那么比较适合使用非严格读/写缓存策略。

ehcache如何根据数据库的修改更新缓存内容?
可以为ehcache定制修改监听器,当监听的内容被修改时,clear相应内容。

    <cache
        name="commandCache"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="0"
        overflowToDisk="true">
        <cacheEventListenerFactory class="com.iding.pos.server.cache.CommandCacheEventListenerFactory"/>
    </cache>

public class OrderCacheEventListener implements CacheEventListener {
    protected static final Logger logger = LoggerFactory.getLogger(OrderCacheEventListener.class);

    public void notifyElementRemoved(Ehcache ehcache, Element element) throws CacheException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void notifyElementPut(Ehcache ehcache, Element element) throws CacheException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void notifyElementUpdated(Ehcache ehcache, Element element) throws CacheException {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void notifyElementExpired(Ehcache ehcache, Element element) {
        PosService posService = (PosService) ServiceLocator.getService("posService");
        // 订单没有正常被POS机处理,所以在这里需要设置订单状态
        long orderId = (Long)element.getObjectValue();
        logger.debug("the order of:" + orderId + " have expired.");
        posService.updateOrderStatus(orderId, Const.POS_RECIVE_FAILD);
        // 从缓存中清除
        ehcache.remove(element.getObjectKey());
       
        // 如果长时间没反应则可能POS机有问题(这里做一下标识)
       
    }

    public void notifyElementEvicted(Ehcache ehcache, Element element) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void notifyRemoveAll(Ehcache ehcache) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void dispose() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public Object clone() throws CloneNotSupportedException {
        return null; //To change body of implemented methods use File | Settings | File Templates.
    }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics