最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring搭配Ehcache實(shí)例解析

 更新時(shí)間:2016年11月16日 14:57:11   作者:我是干勾魚  
這篇文章主要為大家詳細(xì)介紹了Spring搭配Ehcache實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

1 Ehcache簡介

EhCache 是一個(gè)純Java的進(jìn)程內(nèi)緩存框架,具有快速、精干等特點(diǎn),是Hibernate中默認(rèn)的CacheProvider。

Ehcache是一種廣泛使用的開源Java分布式緩存。主要面向通用緩存,Java EE和輕量級(jí)容器。它具有內(nèi)存和磁盤存儲(chǔ),緩存加載器,緩存擴(kuò)展,緩存異常處理程序,一個(gè)gzip緩存servlet過濾器,支持REST和SOAP api等特點(diǎn)。

Ehcache最初是由Greg Luck于2003年開始開發(fā)。2009年,該項(xiàng)目被Terracotta購買。軟件仍然是開源,但一些新的主要功能(例如,快速可重啟性之間的一致性的)只能在商業(yè)產(chǎn)品中使用,例如Enterprise EHCache and BigMemory。維基媒體Foundationannounced目前使用的就是Ehcache技術(shù)。

總之Ehcache還是一個(gè)不錯(cuò)的緩存技術(shù),我們來看看Spring搭配Ehcache是如何實(shí)現(xiàn)的。

2 Spring搭配Ehcache

系統(tǒng)結(jié)果如下:

3 具體配置介紹

有這幾部分的結(jié)合:

src:java代碼,包含攔截器,調(diào)用接口,測試類

src/cache-bean.xml:配置Ehcache,攔截器,以及測試類等信息對(duì)應(yīng)的bean

src/ehcache.xml:Ehcache緩存配置信息

WebRoot/lib:庫

4 詳細(xì)內(nèi)容介紹

4.1 src

4.1.1 攔截器

代碼中首先配置了兩個(gè)攔截器:

第一個(gè)攔截器為:

com.test.ehcache.CacheMethodInterceptor

內(nèi)容如下:

package com.test.ehcache;

import java.io.Serializable;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public class CacheMethodInterceptor implements MethodInterceptor,
 InitializingBean {

 private Cache cache;

 public void setCache(Cache cache) {
 this.cache = cache;
 }

 public CacheMethodInterceptor() {
 super();
 }

 /**
 * 攔截ServiceManager的方法,并查找該結(jié)果是否存在,如果存在就返回cache中的值,
 * 否則,返回?cái)?shù)據(jù)庫查詢結(jié)果,并將查詢結(jié)果放入cache
 */
 public Object invoke(MethodInvocation invocation) throws Throwable {
 //獲取要攔截的類
 String targetName = invocation.getThis().getClass().getName();
 //獲取要攔截的類的方法
 String methodName = invocation.getMethod().getName();
 //獲得要攔截的類的方法的參數(shù)
 Object[] arguments = invocation.getArguments();
 Object result;

 //創(chuàng)建一個(gè)字符串,用來做cache中的key
 String cacheKey = getCacheKey(targetName, methodName, arguments);
 //從cache中獲取數(shù)據(jù)
 Element element = cache.get(cacheKey);

 if (element == null) {
 //如果cache中沒有數(shù)據(jù),則查找非緩存,例如數(shù)據(jù)庫,并將查找到的放入cache

  result = invocation.proceed();
  //生成將存入cache的key和value
  element = new Element(cacheKey, (Serializable) result);
  System.out.println("-----進(jìn)入非緩存中查找,例如直接查找數(shù)據(jù)庫,查找后放入緩存");
  //將key和value存入cache
  cache.put(element);
 } else {
 //如果cache中有數(shù)據(jù),則查找cache

  System.out.println("-----進(jìn)入緩存中查找,不查找數(shù)據(jù)庫,緩解了數(shù)據(jù)庫的壓力");
 }
 return element.getValue();
 }

 /**
 * 獲得cache的key的方法,cache的key是Cache中一個(gè)Element的唯一標(biāo)識(shí),
 * 包括包名+類名+方法名,如:com.test.service.TestServiceImpl.getObject
 */
 private String getCacheKey(String targetName, String methodName,
  Object[] arguments) {
 StringBuffer sb = new StringBuffer();
 sb.append(targetName).append(".").append(methodName);
 if ((arguments != null) && (arguments.length != 0)) {
  for (int i = 0; i < arguments.length; i++) {
  sb.append(".").append(arguments[i]);
  }
 }
 return sb.toString();
 }

 /**
 * implement InitializingBean,檢查cache是否為空 70
 */
 public void afterPropertiesSet() throws Exception {
 Assert.notNull(cache,
  "Need a cache. Please use setCache(Cache) create it.");
 }

}

CacheMethodInterceptor用來攔截以“get”開頭的方法,注意這個(gè)攔截器是先攔截,后執(zhí)行原調(diào)用接口。

還有一個(gè)攔截器:

com.test.ehcache.CacheAfterReturningAdvice

具體內(nèi)容:

package com.test.ehcache;

import java.lang.reflect.Method;
import java.util.List;

import net.sf.ehcache.Cache;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public class CacheAfterReturningAdvice implements AfterReturningAdvice,
 InitializingBean {

 private Cache cache;

 public void setCache(Cache cache) {
 this.cache = cache;
 }

 public CacheAfterReturningAdvice() {
 super();
 }

 public void afterReturning(Object arg0, Method arg1, Object[] arg2,
  Object arg3) throws Throwable {
 String className = arg3.getClass().getName();
 List list = cache.getKeys();
 for (int i = 0; i < list.size(); i++) {
  String cacheKey = String.valueOf(list.get(i));
  if (cacheKey.startsWith(className)) {
  cache.remove(cacheKey);
  System.out.println("-----清除緩存");
  }
 }
 }

 public void afterPropertiesSet() throws Exception {
 Assert.notNull(cache,
  "Need a cache. Please use setCache(Cache) create it.");
 }

}

CacheAfterReturningAdvice用來攔截以“update”開頭的方法,注意這個(gè)攔截器是先執(zhí)行原調(diào)用接口,后被攔截。

4.1.2 調(diào)用接口

接口名稱為:

com.test.service.ServiceManager

具體內(nèi)容如下:

package com.test.service;

import java.util.List;

public interface ServiceManager { 
 public List getObject(); 

 public void updateObject(Object Object); 
}

實(shí)現(xiàn)類名稱為:

com.test.service.ServiceManagerImpl

具體內(nèi)容如下:

package com.test.service;

import java.util.ArrayList;
import java.util.List;

public class ServiceManagerImpl implements ServiceManager {

 @Override
 public List getObject() {
 System.out.println("-----ServiceManager:緩存Cache內(nèi)不存在該element,查找數(shù)據(jù)庫,并放入Cache!");

 return null;
 }

 @Override
 public void updateObject(Object Object) {
 System.out.println("-----ServiceManager:更新了對(duì)象,這個(gè)類產(chǎn)生的cache都將被remove!");
 }

}

4.1.3 測試類

測試類名稱為:

com.test.service.TestMain

具體內(nèi)容為:

package com.test.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMain {

 public static void main(String[] args) {

 String cacheString = "/cache-bean.xml";
 ApplicationContext context = new ClassPathXmlApplicationContext(
  cacheString);
 //獲取代理工廠proxyFactory生成的bean,以便產(chǎn)生攔截效果
 ServiceManager testService = (ServiceManager) context.getBean("proxyFactory");

 // 第一次查找
 System.out.println("=====第一次查找");
 testService.getObject();

 // 第二次查找
 System.out.println("=====第二次查找");
 testService.getObject();

 // 執(zhí)行update方法(應(yīng)該清除緩存)
 System.out.println("=====第一次更新");
 testService.updateObject(null);

 // 第三次查找
 System.out.println("=====第三次查找");
 testService.getObject();
 } 
}

此處要注意,獲取bean是通過代理工廠proxyFactory生產(chǎn)的bean,這樣才會(huì)有攔截效果。

能夠看出來,在測試類里面設(shè)置了四次調(diào)用,執(zhí)行順序?yàn)椋?/p>

第一次查找
第二次查找
第一次更新
第三次查找

4.2 src/cache-bean.xml

cache-bean.xml用來配置Ehcache,攔截器,以及測試類等信息對(duì)應(yīng)的bean,內(nèi)容如下:

<?xml version="1.0" encoding="UTF-8"?> 
 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" 
"http://www.springframework.org/dtd/spring-beans.dtd"> 
<beans> 
 <!-- 引用ehCache 的配置--> 
 <bean id="defaultCacheManager" 
 class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 
 <property name="configLocation"> 
  <value>ehcache.xml</value> 
 </property>
 </bean> 

 <!-- 定義ehCache的工廠,并設(shè)置所使用的Cache的name,即“com.tt” --> 
 <bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> 
 <property name="cacheManager"> 
  <ref local="defaultCacheManager" /> 
 </property>
 <!-- Cache的名稱 -->
 <property name="cacheName"> 
  <value>com.tt</value> 
 </property> 
 </bean> 

 <!-- 創(chuàng)建緩存、查詢緩存的攔截器 --> 
 <bean id="cacheMethodInterceptor" class="com.test.ehcache.CacheMethodInterceptor"> 
 <property name="cache"> 
  <ref local="ehCache" /> 
 </property> 
 </bean>

 <!-- 更新緩存、刪除緩存的攔截器 --> 
 <bean id="cacheAfterReturningAdvice" class="com.test.ehcache.CacheAfterReturningAdvice"> 
 <property name="cache"> 
  <ref local="ehCache" /> 
 </property> 
 </bean>

 <!-- 調(diào)用接口,被攔截的對(duì)象 -->
 <bean id="serviceManager" class="com.test.service.ServiceManagerImpl" /> 

 <!-- 插入攔截器,確認(rèn)調(diào)用哪個(gè)攔截器,攔截器攔截的方法名特點(diǎn)等,此處調(diào)用攔截器com.test.ehcache.CacheMethodInterceptor -->
 <bean id="cachePointCut" 
 class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> 
 <!-- 加入切面,切面為當(dāng)執(zhí)行完print方法后,在執(zhí)行加入的切面 -->
 <property name="advice"> 
  <ref local="cacheMethodInterceptor" /> 
 </property> 
 <property name="patterns"> 
  <list> 
  <!-- 
   ### .表示符合任何單一字元   
   ### +表示符合前一個(gè)字元一次或多次   
   ### *表示符合前一個(gè)字元零次或多次   
   ### \Escape任何Regular expression使用到的符號(hào)   
  -->   
  <!-- .*表示前面的前綴(包括包名),意思是表示getObject方法-->
  <value>.*get.*</value> 
  </list> 
 </property> 
 </bean> 

 <!-- 插入攔截器,確認(rèn)調(diào)用哪個(gè)攔截器,攔截器攔截的方法名特點(diǎn)等,此處調(diào)用攔截器com.test.ehcache.CacheAfterReturningAdvice -->
 <bean id="cachePointCutAdvice" 
 class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> 
 <property name="advice"> 
  <ref local="cacheAfterReturningAdvice" /> 
 </property> 
 <property name="patterns"> 
  <list>
  <!-- .*表示前面的前綴(包括包名),意思是updateObject方法--> 
  <value>.*update.*</value> 
  </list> 
 </property> 
 </bean>

 <!-- 代理工廠 -->
 <bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean">
 <!-- 說明調(diào)用接口bean名稱 -->
 <property name="target"> 
  <ref local="serviceManager" /> 
 </property> 
 <!-- 說明攔截器bean名稱 -->
 <property name="interceptorNames"> 
  <list> 
  <value>cachePointCut</value> 
  <value>cachePointCutAdvice</value> 
  </list> 
 </property> 
 </bean> 
</beans>

各個(gè)bean的內(nèi)容都做了注釋說明,值得注意的是,不要忘了代理工廠bean。

4.3 src/ehcache.xml

ehcache.xml中存儲(chǔ)Ehcache緩存配置的詳細(xì)信息,內(nèi)容如下:

<?xml version="1.0" encoding="UTF-8"?> 
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
 <!-- 緩存文件位置 -->
 <diskStore path="D:\\temp\\cache" /> 

 <defaultCache maxElementsInMemory="1000" eternal="false" 
 timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /> 
 <!-- 定義緩存文件信息,其中“com.tt”為緩存文件的名字 --> 
 <cache name="com.tt" maxElementsInMemory="10000" eternal="false" 
 timeToIdleSeconds="300000" timeToLiveSeconds="600000" overflowToDisk="true" /> 
</ehcache>

能夠看到緩存的存儲(chǔ)的存儲(chǔ)位置設(shè)置為“D:\temp\cache”,緩存名稱設(shè)置成了“com.tt”,如圖:

4.4 WebRoot/lib

所需的java庫,詳見開頭的系統(tǒng)結(jié)構(gòu)圖片,此處略。

5 測試

執(zhí)行測試類,測試結(jié)果如下:

通過執(zhí)行結(jié)果我們能夠看出:

第一次查找被攔截后發(fā)現(xiàn)是首次攔截,還沒有緩存Cache,所以先執(zhí)行一下原有接口類,得到要查詢的數(shù)據(jù),有可能是通過數(shù)據(jù)庫查詢得到的,然后再生成Cache,并將查詢得到的數(shù)據(jù)放入Cache。

第二次查找被攔截后發(fā)現(xiàn)已經(jīng)存在Cache,于是不再執(zhí)行原有接口類,也就是不再查詢數(shù)據(jù)庫啦,直接通過Cache得到查詢數(shù)據(jù)。當(dāng)然這里只是簡單打印一下。

然后是第一次更新,被攔截后所做的操作是將Cache中的數(shù)據(jù)全部存入數(shù)據(jù)庫,并將Cache刪除。

最后是第三次查詢,被攔截后又發(fā)現(xiàn)系統(tǒng)不存在Cache,于是執(zhí)行原接口類查詢數(shù)據(jù)庫,創(chuàng)建Cache,并將新查詢得到的數(shù)據(jù)放入Cache。同第一次查詢的方式是一樣的。

至此我們就實(shí)現(xiàn)了Spring搭配Ehcache所需要完成的操作。

6 附件源代碼

附件源代碼可以從我的github網(wǎng)站上獲取。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • mybatis plus時(shí)間判斷問題

    mybatis plus時(shí)間判斷問題

    在MyBatisPlus中,時(shí)間判斷可以通過XML轉(zhuǎn)義的方式實(shí)現(xiàn),例如使用>、<、<>、>=、<=進(jìn)行比較,這種方法涉及到SQL符號(hào)的轉(zhuǎn)義,確保查詢語句的安全性和準(zhǔn)確性,特別是在處理大于、小于和等于等邏輯時(shí),正確的轉(zhuǎn)義能夠防止SQL注入等安全問題
    2024-09-09
  • 在Spring異步調(diào)用中傳遞上下文的方法

    在Spring異步調(diào)用中傳遞上下文的方法

    這篇文章主要給大家介紹了關(guān)于如何在Spring異步調(diào)用中傳遞上下文的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • Java數(shù)據(jù)結(jié)構(gòu)之二叉查找樹的實(shí)現(xiàn)

    Java數(shù)據(jù)結(jié)構(gòu)之二叉查找樹的實(shí)現(xiàn)

    二叉查找樹(亦稱二叉搜索樹、二叉排序樹)是一棵二叉樹,且各結(jié)點(diǎn)關(guān)鍵詞互異,其中根序列按其關(guān)鍵詞遞增排列。本文將通過示例詳細(xì)講解二叉查找樹,感興趣的可以了解一下
    2022-03-03
  • Java concurrency集合之ConcurrentHashMap_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    Java concurrency集合之ConcurrentHashMap_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    這篇文章主要介紹了Java concurrency集合之ConcurrentHashMap的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • Java注解的Retention和RetentionPolicy實(shí)例分析

    Java注解的Retention和RetentionPolicy實(shí)例分析

    這篇文章主要介紹了Java注解的Retention和RetentionPolicy,結(jié)合實(shí)例形式分析了Java注解Retention和RetentionPolicy的基本功能及使用方法,需要的朋友可以參考下
    2019-09-09
  • Java語言中flush()函數(shù)作用及使用方法詳解

    Java語言中flush()函數(shù)作用及使用方法詳解

    這篇文章主要介紹了Java語言中flush函數(shù)作用及使用方法詳解,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-01-01
  • IntelliJ IDEA設(shè)置代碼的快捷編輯模板Live Templates

    IntelliJ IDEA設(shè)置代碼的快捷編輯模板Live Templates

    今天小編就為大家分享一篇關(guān)于IntelliJ IDEA設(shè)置代碼的快捷編輯模板Live Templates,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-10-10
  • RestTemplate返回值中文亂碼問題

    RestTemplate返回值中文亂碼問題

    這篇文章主要介紹了RestTemplate返回值中文亂碼問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • Springmvc實(shí)現(xiàn)文件上傳

    Springmvc實(shí)現(xiàn)文件上傳

    這篇文章主要為大家詳細(xì)介紹了Springmvc實(shí)現(xiàn)文件上傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-10-10
  • java實(shí)現(xiàn)http的Post、Get、代理訪問請(qǐng)求

    java實(shí)現(xiàn)http的Post、Get、代理訪問請(qǐng)求

    這篇文章主要為大家提供了java實(shí)現(xiàn)http的Post、Get、代理訪問請(qǐng)求的相關(guān)代碼,感興趣的小伙伴們可以參考一下
    2016-01-01

最新評(píng)論

旺苍县| 内江市| 北辰区| 墨脱县| 皋兰县| 时尚| 洛浦县| 万山特区| 宣恩县| 弋阳县| 扶余县| 满城县| 桑日县| 原阳县| 长春市| 陕西省| 台北县| 益阳市| 多伦县| 云阳县| 临邑县| 宜兰市| 麟游县| 柳河县| 华蓥市| 沈阳市| 清新县| 太保市| 中方县| 屏东市| 长子县| 长岛县| 镇安县| 乌审旗| 长垣县| 重庆市| 精河县| 江阴市| 光山县| 洪雅县| 墨玉县|