javaweb项目搭建ehcache缓存系统
轉(zhuǎn)載自??javaweb項(xiàng)目搭建ehcache緩存系統(tǒng)
EhCache 是一個(gè)純Java的進(jìn)程內(nèi)緩存框架,具有快速、精干等特點(diǎn),是Hibernate中默認(rèn)的CacheProvider,同時(shí)在項(xiàng)目開發(fā)中也被廣泛使用到。接下來就以用戶緩存為例,基于javaweb項(xiàng)目來搭建ehcache緩存系統(tǒng)。
主要涉及核心原理和實(shí)現(xiàn)要點(diǎn):項(xiàng)目是基于spring框架來統(tǒng)一管理和配置bean的,所以在spring中配置緩存,定義EhCacheManagerFactoryBean,同時(shí)指向其ehcache配置文件ehcache.xml,ehcache.xml則有我們自己根據(jù)項(xiàng)目情況來定義一些緩存策略,如:cache中元素的生存時(shí)間、cache 中最多可以存放的元素的數(shù)量和內(nèi)存存儲(chǔ)與釋放策略等等。java代碼中則可以定義一個(gè)統(tǒng)一的緩存管理類去持有net.sf.ehcache.CacheManager實(shí)例,來代理往數(shù)據(jù)庫(kù)中操作數(shù)據(jù)的行為。關(guān)于CacheManager實(shí)例的獲取,則可以通過實(shí)現(xiàn)ApplicationContextAware, DisposableBean接口,分別重寫其setApplicationContext()方法,注入ApplicationContext到靜態(tài)變量中和destroy()方法,在ApplicationContext關(guān)閉時(shí)清理靜態(tài)變量。這樣以靜態(tài)變量保存Spring ApplicationContext, 可在任何代碼任何地方任何時(shí)候取出ApplicaitonContext,進(jìn)而調(diào)用其getBean()方法來獲得CacheManager實(shí)例。拿數(shù)據(jù)是先getByCache(),若緩存中存在數(shù)據(jù)則直接返回該數(shù)據(jù),若緩存中不存在數(shù)據(jù),再執(zhí)行g(shù)etByDb(),從數(shù)據(jù)庫(kù)中拿數(shù)據(jù),同時(shí)將數(shù)據(jù)存進(jìn)緩存中。
1、首先從web.xml部署文件入口進(jìn)行配置
<!-- 應(yīng)用程序Spring上下文配置 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:applicationContext*.xml,</param-value></context-param> <!-- 自定義監(jiān)聽器 繼承自spring上下文加載監(jiān)聽器 --><listener><listener-class>com.schoolnet.sys.listener.WebContextListener</listener-class></listener>繼承自spring上下文加載監(jiān)聽器的WebContextListener類,可以在web啟動(dòng)時(shí)做一些處理
WebContextListener .java
public class WebContextListener extends org.springframework.web.context.ContextLoaderListener {@Overridepublic WebApplicationContext initWebApplicationContext(ServletContext servletContext) {if (!printKeyLoadMessage()){return null;}return super.initWebApplicationContext(servletContext);}private static boolean printKeyLoadMessage(){StringBuilder sb = new StringBuilder();sb.append("\r\n======================================================================\r\n");sb.append("\r\n 歡迎使用 校園網(wǎng) - EhCache緩存系統(tǒng)搭建\r\n");sb.append("\r\n======================================================================\r\n");System.out.println(sb.toString());return true;} }2、applicationContex.xml中配置ehcache緩存
<!-- 加載配置屬性文件 --><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="fileEncoding" value="UTF-8" /><property name="locations"><list><value>classpath:schoolnet.properties</value></list></property></bean> <!-- 緩存配置 --><bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"><property name="configLocation" value="classpath:${ehcache.configFile}" /></bean>3、schoolnet.properties
ehcache.configFile=cache/ehcache.xml(源碼包下的cache文件夾中)4、ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache updateCheck="false" name="defaultCache"><diskStore path="../temp/jeesite/ehcache" /><!-- 默認(rèn)緩存配置. --><defaultCache maxEntriesLocalHeap="100" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600"overflowToDisk="true" maxEntriesLocalDisk="100000" /><!-- 系統(tǒng)緩存 --><cache name="sysCache" maxEntriesLocalHeap="100" eternal="true" overflowToDisk="true"/><!-- 用戶緩存 --><cache name="userCache" maxEntriesLocalHeap="100" eternal="true" overflowToDisk="true"/><!-- 系統(tǒng)活動(dòng)會(huì)話緩存 --><cache name="activeSessionsCache" maxEntriesLocalHeap="10000" overflowToDisk="true"eternal="true" timeToLiveSeconds="0" timeToIdleSeconds="0"diskPersistent="true" diskExpiryThreadIntervalSeconds="600"/><!-- 簡(jiǎn)單頁(yè)面緩存<cache name="SimplePageCachingFilter" maxEntriesLocalHeap="100" eternal="false" overflowToDisk="true"timeToIdleSeconds="120" timeToLiveSeconds="120" memoryStoreEvictionPolicy="LFU"/> --></ehcache>一些配置參數(shù)的說明
maxElementsInMemory :cache 中最多可以存放的元素的數(shù)量。如果放入cache中的元素超過這個(gè)數(shù)值,有兩種情況:1、若overflowToDisk的屬性值為true,會(huì)將cache中多出的元素放入磁盤文件中。2、若overflowToDisk的屬性值為false,會(huì)根據(jù)memoryStoreEvictionPolicy的策略替換cache中原有的元素。
eternal :意思是是否永駐內(nèi)存。如果值是true,cache中的元素將一直保存在內(nèi)存中,不會(huì)因?yàn)闀r(shí)間超時(shí)而丟失,所以在這個(gè)值為true的時(shí)候,timeToIdleSeconds和timeToLiveSeconds兩個(gè)屬性的值就不起作用了。
timeToIdleSeconds :就是訪問這個(gè)cache中元素的最大間隔時(shí)間。如果超過這個(gè)時(shí)間沒有訪問這個(gè)cache中的某個(gè)元素,那么這個(gè)元素將被從cache中清除。
timeToLiveSeconds : 這是cache中元素的生存時(shí)間。意思是從cache中的某個(gè)元素從創(chuàng)建到消亡的時(shí)間,從創(chuàng)建開始計(jì)時(shí),當(dāng)超過這個(gè)時(shí)間,這個(gè)元素將被從cache中清除。
overflowToDisk :溢出是否寫入磁盤。系統(tǒng)會(huì)根據(jù)標(biāo)簽<diskStore path="java.io.tmpdir"/> 中path的值查找對(duì)應(yīng)的屬性值,如果系統(tǒng)的java.io.tmpdir的值是 D:/temp,寫入磁盤的文件就會(huì)放在這個(gè)文件夾下。文件的名稱是cache的名稱,后綴名的data。如:CACHE_FUNC.data。這個(gè)屬性在解釋maxElementsInMemory的時(shí)候也已經(jīng)說過了。
diskExpiryThreadIntervalSeconds ?:磁盤緩存的清理線程運(yùn)行間隔
memoryStoreEvictionPolicy :內(nèi)存存儲(chǔ)與釋放策略。有三個(gè)值:
LRU -least recently used
LFU -least frequently used
FIFO-first in first out, the oldest element by creation time
diskPersistent : 是否持久化磁盤緩存。當(dāng)這個(gè)屬性的值為true時(shí),系統(tǒng)在初始化的時(shí)候會(huì)在磁盤中查找文件名為cache名稱,后綴名為index的的文件,如CACHE_FUNC.index 。這個(gè)文件中存放了已經(jīng)持久化在磁盤中的cache的index,找到后把cache加載到內(nèi)存。要想把cache真正持久化到磁盤,寫程序時(shí)必須注意,在是用net.sf.ehcache.Cache的void put (Element element)方法后要使用void flush()方法。
5、CacheUtils.java
/*** Cache工具類*/ public class CacheUtils {private static CacheManager cacheManager = ((CacheManager)SpringContext.getBean("cacheManager"));private static final String SYS_CACHE = "sysCache";/*** 獲取SYS_CACHE緩存* @param key* @return*/public static Object get(String key) {return get(SYS_CACHE, key);}/*** 寫入SYS_CACHE緩存* @param key* @return*/public static void put(String key, Object value) {put(SYS_CACHE, key, value);}/*** 從SYS_CACHE緩存中移除* @param key* @return*/public static void remove(String key) {remove(SYS_CACHE, key);}/*** 獲取緩存* @param cacheName* @param key* @return*/public static Object get(String cacheName, String key) {Element element = getCache(cacheName).get(key);return element==null?null:element.getObjectValue();}/*** 寫入緩存* @param cacheName* @param key* @param value*/public static void put(String cacheName, String key, Object value) {Element element = new Element(key, value);getCache(cacheName).put(element);}/*** 從緩存中移除* @param cacheName* @param key*/public static void remove(String cacheName, String key) {getCache(cacheName).remove(key);}/*** 獲得一個(gè)Cache,沒有則創(chuàng)建一個(gè)。* @param cacheName* @return*/private static Cache getCache(String cacheName){Cache cache = cacheManager.getCache(cacheName);if (cache == null){cacheManager.addCache(cacheName);cache = cacheManager.getCache(cacheName);cache.getCacheConfiguration().setEternal(true);}return cache;}public static CacheManager getCacheManager() {return cacheManager;}} 6、SpringContext.java,用類獲得ApplicationContext實(shí)例@Component public class SpringContext implements ApplicationContextAware,DisposableBean{private static ApplicationContext applicationContext;/*** 取得存儲(chǔ)在靜態(tài)變量中的ApplicationContext.*/@Overridepublic void setApplicationContext(ApplicationContext context)throws BeansException {try {applicationContext=context;} catch (Exception e) {e.printStackTrace();}}/*** 從靜態(tài)變量applicationContext中取得Bean, 自動(dòng)轉(zhuǎn)型為所賦值對(duì)象的類型.*/public static <T> T getBean(String name){return (T) applicationContext.getBean(name);}public static String[] getBeanNamesForType(Class<?> type){return applicationContext.getBeanNamesForType(type);}/*** 實(shí)現(xiàn)DisposableBean接口, 在Context關(guān)閉時(shí)清理靜態(tài)變量.*/@Overridepublic void destroy() throws Exception {applicationContext = null;} }7、UserUtils.java
/*** 用戶工具類*/ public class UserUtils {private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);private static Map<String, Object> cacheMap;/*** 根據(jù)ID獲取用戶* @param id* @return 取不到返回null*/public static User getUser(String id){User user = (User)CacheUtils.get("userCache", "id_" + id);if (user == null){user = userDao.get(id);if (user == null){return null;}CacheUtils.put("userCache", "id_" + user.getId(), user);CacheUtils.put("userCache", "ln" + user.getLoginName(), user);}return user;}/*** 根據(jù)登錄名獲取用戶* @param loginName* @return 取不到返回null*/public static User getByLoginName(String loginName){User user = (User)CacheUtils.get("userCache", "ln" + loginName);if (user == null){user = userDao.getByLoginName(new User(null, loginName));if (user == null){return null;}CacheUtils.put("userCache", "id_" + user.getId(), user);CacheUtils.put("userCache", "ln" + user.getLoginName(), user);}return user;}/*** 清除用戶緩存* @param user*/public static void clearCache(User user){CacheUtils.remove("userCache", "id_" + user.getId());CacheUtils.remove("userCache", "ln" + user.getLoginName());CacheUtils.remove("userCache", "ln" + user.getOldLoginName());} }總結(jié)
以上是生活随笔為你收集整理的javaweb项目搭建ehcache缓存系统的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 4000左右电脑配置清单(电脑配置推荐4
- 下一篇: 初识分布式系统