Ehcache中Cache预热机制

Cache预热机制简介

Ehcache在程序启动的时候并不会立即去加载位于磁盘上的数据到内存,而是在数据被用到的时候去加载(lazy load)。因此在cache启动的时候,其内部没有数据。如果我们想在用到这些数据之前,它们全部被装载进内存,应该怎么做?

Ehcache提供了BootstrapCacheLoader机制来解决这个问题,在Cache被激活之前,它会得到运行。并且有两种模式:同步和异步。如果是同步模式,在CacheMana启动之前,加载便会完成;如果是异步模式,在CacheManager启动的时候,加载会在后台继续,而不是等到所需数据被需要的时候。

具体实现

我们只需要实现接口BootstrapCacheLoader定义自己的加载器MyBootstrapCacheLoader,继承BootstrapCacheLoaderFactory实现一个具体的加载工厂MyBootstrapCacheLoaderFactory即可实现数据的预热。

MyBootstrapCacheLoader负责实现怎么将数据加载进Cache,我们可以进行个性化的实现。MyBootstrapCacheLoaderFactory是一个具体的加载工厂,负责创建加载器实例,我们需要实现一些抽象方法。

下面看具体的代码实现(Java)。

MyBootstrapCacheLoader.java:

/*** * Copyright (c) 2004-2014 All Rights Reserved.*/
package com..test.encache;import java.util.List;import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.bootstrap.BootstrapCacheLoader;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** * @author * @version $Id: CustomBootstrapCacheLoader.java, v 0.1 2014年10月18日 上午10:57:26  Exp $*/
public class MyBootstrapCacheLoader implements BootstrapCacheLoader {private static final Logger logger = LoggerFactory.getLogger(MyBootstrapCacheLoaderFactory.class);StatesDAO                   statesDAO;boolean                     asynchronous;/** * @see net.sf.ehcache.bootstrap.BootstrapCacheLoader#load(net.sf.ehcache.Ehcache)*/public void load(Ehcache cache) throws CacheException {logger.info("load your cache with whatever you want....");List keys = cache.getKeys();for (int i = 0; i < keys.size(); i++) {logger.info("keys->" + keys.get(i));}try {List<String> dataList = getStatesDAO().findAllStates();cache.put(new Element(CacheConstants.KEY_ARRAY[0], dataList.get(0)));cache.put(new Element(CacheConstants.KEY_ARRAY[1], dataList.get(1)));} catch (Exception e) {// TODO Auto-generated catch block e.printStackTrace();}logger.info("load end....");}/** * @see net.sf.ehcache.bootstrap.BootstrapCacheLoader#isAsynchronous()*/public boolean isAsynchronous() {return asynchronous;}/** * @see java.lang.Object#clone()*/@Overridepublic Object clone() throws CloneNotSupportedException {return super.clone();}public StatesDAO getStatesDAO() {return statesDAO;}public void setStatesDAO(StatesDAO statesDAO) {this.statesDAO = statesDAO;}/*** Setter method for property <tt>asynchronous</tt>.* * @param asynchronous value to be assigned to property asynchronous*/public void setAsynchronous(boolean asynchronous) {this.asynchronous = asynchronous;}}

MyBootstrapCacheLoaderFactory.java

/*** * Copyright (c) 2004-2014 All Rights Reserved.*/
package com.test.encache;import java.util.Properties;import net.sf.ehcache.bootstrap.BootstrapCacheLoader;
import net.sf.ehcache.bootstrap.BootstrapCacheLoaderFactory;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;/*** bootstrap cache loader* * @author * @version $Id: MyBootstrapCacheLoaderFactory.java, v 0.1 2014年10月17日 下午8:02:55  Exp $*/
public class MyBootstrapCacheLoaderFactory extends BootstrapCacheLoaderFactory {private final String ASYNCHRONOUS_PROPERTY_KEY = "ASYNCHRONOUS";@Autowiredprivate StatesDAO    statesDAO;public MyBootstrapCacheLoaderFactory() {super();// TODO Auto-generated constructor stub }private static final Logger logger = LoggerFactory.getLogger(MyBootstrapCacheLoaderFactory.class);@Overridepublic BootstrapCacheLoader createBootstrapCacheLoader(Properties properties) {logger.info("MyBootstrapCacheLoaderFactory : create a BootstrapCacheLoader");MyBootstrapCacheLoader loader = new MyBootstrapCacheLoader();statesDAO = new StatesDAO();loader.setStatesDAO(statesDAO);loader.setAsynchronous(getAsyncFromProperty(properties));return loader;}private boolean getAsyncFromProperty(Properties properties) {String asynchronous = properties.getProperty(ASYNCHRONOUS_PROPERTY_KEY);return Boolean.valueOf(asynchronous);}
}

使用了Cache的读取磁盘数据的方法在StatesDAO类中,对此我们只是进行了模拟,从数据库中读取数据。

StatesDAO.java

/*** * Copyright (c) 2004-2014 All Rights Reserved.*/
package com.test.encache;import java.util.ArrayList;
import java.util.List;import com.googlecode.ehcache.annotations.Cacheable;/*** * @author * @version $Id: StatesDAO.java, v 0.1 2014年10月17日 下午8:07:05  Exp $*/
public class StatesDAO {//annotation based caching and the name of cache should be defined in ehcache.xml. @Cacheable(cacheName = "stateCache")public List<String> findAllStates() {List<String> dataList = new ArrayList<String>();//your call to database that returns a list of objects  dataList.add("value1");dataList.add("value2");return dataList;}
}

Cache配置myehcache.xml:

<ehcache><diskStore path="D://localcache"/><cache name="stateCache" maxEntriesLocalHeap="10000" maxEntriesLocalDisk="1000" eternal="false" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off"><bootstrapCacheLoaderFactory class="com.test.encache.MyBootstrapCacheLoaderFactory"  properties="ASYNCHRONOUS=true"/>
</cache><cache name="stateCache2" maxEntriesLocalHeap="10000" maxEntriesLocalDisk="1000" eternal="false" diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" transactionalMode="off"><bootstrapCacheLoaderFactory class="com.test.encache.MyBootstrapCacheLoaderFactory"  properties="ASYNCHRONOUS=false"/>
</cache></ehcache>

CacheManager配置ApplicationContext.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-springhttp://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd"default-autowire="byType"><ehcache:annotation-driven cache-manager="ehCacheManager" /> <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation"> <value>src/config/myehcache.xml</value> </property></bean> </beans>

最后是测试代码:BootstrapCacheLoaderTest.java:

/*** * Copyright (c) 2004-2014 All Rights Reserved.*/
package com.test.encache;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;/*** * @author * @version $Id: BootstrapCacheLoader.java, v 0.1 2014年10月18日 上午11:31:06 Exp $*/
public class BootstrapCacheLoaderTest {private static String       log4jFileName      = "src/config/log4j.properties";private static String       xmlFileName        = "src/config/ApplicationContext.xml";private static String       ehcacheXmlFileName = "src/config/myehcache.xml";private static final Logger logger             = LoggerFactory.getLogger(BootstrapCacheLoaderTest.class);private static CacheManager ehCacheManager;public static void main(String[] args) {configProperty();xmlLoad(ehcacheXmlFileName);String[] cacheNamesStrings = ehCacheManager.getCacheNames();logger.info("the number of caches in ehCacheManager : " + cacheNamesStrings.length);Cache cache = ehCacheManager.getCache(CacheConstants.CACHE_NAME1);Element element = cache.get(CacheConstants.KEY_ARRAY[0]);logger.info("the element of key  " + CacheConstants.KEY_ARRAY[0] + " is " + element);}/*** config properties* */private static void configProperty() {Properties properties = new Properties();FileInputStream istream;try {istream = new FileInputStream(log4jFileName);properties.load(istream);istream.close();} catch (FileNotFoundException e) {logger.error("File not found", e);} catch (IOException e) {logger.error("load file erroe", e);} finally {}//properties.setProperty("log4j.appender.file.File",logFile); PropertyConfigurator.configure(properties);logger.info("config properties success.");}private static void xmlLoad(String fileName) {ApplicationContext ctx = new FileSystemXmlApplicationContext(xmlFileName);ehCacheManager = (CacheManager) ctx.getBean("ehCacheManager");}
}

输出结果:
2014-10-18 15:17:45 INFO  BootstrapCacheLoaderTest:71 - config properties success.
2014-10-18 15:17:45 INFO  FileSystemXmlApplicationContext:513 - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@687b6889: startup date [Sat Oct 18 15:17:45 CST 2014]; root of context hierarchy
2014-10-18 15:17:45 INFO  XmlBeanDefinitionReader:316 - Loading XML bean definitions from file [D:\code\test\encache\src\config\ApplicationContext.xml]
2014-10-18 15:17:45 INFO  EhCacheManagerFactoryBean:136 - Initializing EhCache CacheManager
2014-10-18 15:17:46 INFO  MyBootstrapCacheLoaderFactory:38 - MyBootstrapCacheLoaderFactory : create a BootstrapCacheLoader
2014-10-18 15:17:46 INFO  MyBootstrapCacheLoaderFactory:38 - MyBootstrapCacheLoaderFactory : create a BootstrapCacheLoader
2014-10-18 15:17:46 INFO  MyBootstrapCacheLoaderFactory:34 - load your cache with whatever you want....
2014-10-18 15:17:46 INFO  MyBootstrapCacheLoaderFactory:51 - load end....
2014-10-18 15:17:46 INFO  MyBootstrapCacheLoaderFactory:34 - load your cache with whatever you want....
2014-10-18 15:17:46 INFO  MyBootstrapCacheLoaderFactory:51 - load end....
2014-10-18 15:17:46 INFO  BootstrapCacheLoaderTest:43 - the number of caches in ehCacheManager : 2
2014-10-18 15:17:46 INFO  BootstrapCacheLoaderTest:46 - the element of key  KEY1 is [ key = KEY1, value=value1, version=1, hitCount=1, CreationTime = 1413616666238, LastAccessTime = 1413616666302 ]

参考资料

Ehcache关于预热机制的官方文档

Load EhCache diskstore content into memory

How to load data to Ehcache when the application starts

Java缓存Ehcache-Ehcache的Cache预热机制及代码实现(Cache Warming for multi-tier Caches)相关推荐

  1. Java缓存Ehcache-核心类和方法介绍及代码实例

    Ehcache中核心类和方法 EhCache里面有一个CacheManager类型,它负责管理cache.Cache里面存储着Element对象,Element必须是key-value对.Cache是 ...

  2. java 等待 唤醒_Java之等待唤醒机制的代码实现

    各位小伙伴们大家好,在之前的文章中,小编陆陆续续讲了很多关于线程还有等待唤醒机制的一些知识,这次小编要讲的是等待唤醒机制的代码实现. 就用快递员送快递,我们取快递来举例,首先要进行需求分析.主要有两个 ...

  3. java 抛异常给上级_java异常处理机制(示例代码)

    Exception 类的层次 java中所有的异常类是从 java.lang.Exception 类继承的子类. 而Exception 类是 Throwable (可抛出的)类的子类.除了Except ...

  4. java 项目做多级缓存_【开源项目系列】如何基于 Spring Cache 实现多级缓存(同时整合本地缓存 Ehcache 和分布式缓存 Redis)...

    一.缓存 当系统的并发量上来了,如果我们频繁地去访问数据库,那么会使数据库的压力不断增大,在高峰时甚至可以出现数据库崩溃的现象.所以一般我们会使用缓存来解决这个数据库并发访问问题,用户访问进来,会先从 ...

  5. Java 开源分布式缓存框架Ehcache

    Ehcache 是一个Java实现的开源分布式缓存框架,EhCache 可以有效地减轻数据库的负载,可以让数据保存在不同服务器的内存中,在需要数据的时候可以快速存取.同时EhCache 扩展非常简单, ...

  6. Java缓存框架使用EhCache结合Spring AOP

    Java缓存框架使用EhCache结合Spring AOP 一.Ehcache简介     EhCache是一个纯Java的进程内缓存框架,具有如下特点:     1. 快速简单,非常容易和应用集成. ...

  7. Java的进程内缓存框架:EhCache (转)

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. Ehcache缓存的特点: 1. 快速. 2. 简单. 3. 多种缓存 ...

  8. 【Java】ehcache | EhCache | 集成缓存EhCache

    一.说明 1.maven项目 2.SpringBoot项目 二.解决方案 1.引入依赖 <!--ehcache--> <dependency><groupId>ne ...

  9. Spring Boot 揭秘与实战(二) 数据缓存篇 - EhCache

    文章目录 1. EhCache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 EhCache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门 ...

最新文章

  1. reboot 百度网盘资源
  2. 计算机视觉开源库OpenCV之CommandLineParser使用方法
  3. Java并发编程:进程和线程之由来
  4. 给字符串对象定义一个repeat功能。当传入一个整数n时,它会返回重复n次字符串的结果。
  5. ISE14.7兼容性问题集锦
  6. 面向对象封装之无参无返,无参有返
  7. Sqlserver2008相关配置问题
  8. 小米10鸿蒙版,小米10青春版高清渲染图公布:轻薄得不像5G手机
  9. 从我的简历再谈测试分类
  10. Extjs 判断对象是非为null或者为空字符串
  11. Oracle 数据库维护知识
  12. [转]企业网站首页设计常见的6种布局方式
  13. [UOJ386]鸽子固定器
  14. C# Dictionary键值对 创建,增加,删除,清空
  15. MySQL创建商品入库和出库后库存更新的触发器
  16. 用Python讲述:地理“经纬度”数据的4种转换方法!
  17. 大数据-Redis基础
  18. 关于运行npm install报[..................] / idealTree:WEB-48403: sill idealTree buildDeps的问题
  19. 头哥实践教学平台 CC++程序设计(计算机程序设计)基本输入输出 第2关:整数四则运算表达式的输出格式控制
  20. UEFI0067:A PCIe link training failure is observed in PCIe Slot 3 and the link is disabled. (已解决)

热门文章

  1. 电脑显卡接口类型:VGA、HDMI、DP
  2. TypeScript函数
  3. 嵌入式wifi 芯片 推荐_人工智能对汽车芯片设计的影响
  4. layui 日期格式不正确(date、datetime)区别
  5. vue项目+富文本编辑器ueditor - 资源篇
  6. win10 快捷键 - 采矿篇
  7. IE下 显示图片会多出一个边框的问题
  8. 2019计算机应用基础期末考试试题,2019-2020年度公共课计算机应用基础考试试题附答案...
  9. python编程关键字_python编程关键字
  10. java 进制转换算法_算法笔记_033:十六进制转八进制(Java)