Ehcache結(jié)合Spring

本章介紹Ehcache結(jié)合Spring實現(xiàn)服務(wù)層的緩存斗搞,其他還有數(shù)據(jù)層緩存和頁面緩存埃元。

添加依賴

<dependency>
  <groupId>com.googlecode.ehcache-spring-annotations</groupId>
  <artifactId>ehcache-spring-annotations</artifactId> 
  <version>1.2.0</version> 
</dependency>

spring配置文件

<?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:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:cache="http://www.springframework.org/schema/cache"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  
                        http://www.springframework.org/schema/cache  
                        http://www.springframework.org/schema/cache/spring-cache-3.2.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
    
    <context:component-scan base-package="com.tmg" />  
    <!-- SpringMVC配置 -->  
    <mvc:annotation-driven/>  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/"/>  
        <property name="suffix" value=".jsp"/>  
    </bean>  
    <mvc:view-controller path="/" view-name="forward:/index.jsp"/>  
      
    <!-- 緩存配置 -->  
    <!-- 啟用緩存注解功能(請將其配置在Spring主配置文件中) -->  
    <cache:annotation-driven cache-manager="cacheManager"/>  
    <!-- Spring自帶的Cache!!! Spring自己的基于java.util.concurrent.ConcurrentHashMap實現(xiàn)的緩存管理器(該功能是從Spring3.1開始提供的) -->  
    <!--   
    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">  
        <property name="caches">  
            <set>  
                <bean name="movieFindCache" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"/>  //對應(yīng)@Cacheable(value="movieFindCache"
            </set>  
        </property>  
    </bean>  
     -->  
    <!-- 若只想使用Spring自身提供的緩存器,則注釋掉下面的兩個關(guān)于Ehcache配置的bean,并啟用上面的SimpleCacheManager即可 -->  
    <!-- Spring提供的基于的Ehcache實現(xiàn)的緩存管理器 -->  
    <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
        <property name="configLocation" value="classpath:ehcache.xml"/>  
        <!-- <property name="shared" value="true"/> true時為單例-->
    </bean>  
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">  
        <property name="cacheManager" ref="cacheManagerFactory"/>  
    </bean>  
</beans>  

在Service層注解

import java.util.Map;  
import java.util.concurrent.ConcurrentHashMap;  
import org.springframework.cache.annotation.CacheEvict;  
import org.springframework.cache.annotation.Cacheable;  
import org.springframework.stereotype.Service;  
@Service  
public class UserService {  
    private Map<String, String> usersData = new ConcurrentHashMap<String, String>();  
      
    public UserService(){  
        System.out.println("用戶數(shù)據(jù)初始化..開始");  
        usersData.put("1", "test1");  
        usersData.put("2", "test2");  
        System.out.println("用戶數(shù)據(jù)初始化..完畢");  
    }  
      
    //將查詢到的數(shù)據(jù)緩存到movieFindCache中,并使用方法名稱加上參數(shù)中的userNo作為緩存的key  
    //通常更新操作只需刷新緩存中的某個值,所以為了準(zhǔn)確的清除特定的緩存,故定義了這個唯一的key,從而不會影響其它緩存值  
    @Cacheable(value="movieFindCache", key="'get'+#userNo")  
    public String get(String userNo){  
        System.out.println("數(shù)據(jù)庫中查到此用戶號[" + userNo + "]對應(yīng)的用戶名為[" + usersData.get(userNo) + "]");  
        return usersData.get(userNo);  
    }  
      
    @CacheEvict(value="movieFindCache", key="'get'+#userNo")  
    public void update(String userNo){  
        System.out.println("移除緩存中此用戶號[" + userNo + "]對應(yīng)的用戶名[" + usersData.get(userNo) + "]的緩存");  
    }  
      
    //allEntries為true表示清除value中的全部緩存,默認(rèn)為false  
    @CacheEvict(value="movieFindCache", allEntries=true)  
    public void removeAll(){  
        System.out.println("移除緩存中的所有數(shù)據(jù)");  
    }  
} 

Controller層

import javax.annotation.Resource;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import com.jadyer.service.UserService;  

@Controller  
@RequestMapping("cacheTest")  
public class UserController {  
    @Resource  
    private UserService userService;  
      
    @RequestMapping(value="/get/{userNo}", method=RequestMethod.GET)  
    public String get(@PathVariable String userNo, Model model){  
        String username = userService.get(userNo);  
        model.addAttribute("username", username);  
        return "getUser";  
    }  
      
    @RequestMapping(value="/update/{userNo}", method=RequestMethod.GET)  
    public String update(@PathVariable String userNo, Model model){  
        userService.update(userNo);  
        model.addAttribute("userNo", userNo);  
        return "updateUser";  
    }  
      
    @RequestMapping(value="/removeAll", method=RequestMethod.GET)  
    public String removeAll(){  
        userService.removeAll();  
        return "removeAllUser";  
    }  
}  

要點:
在spring配置文件:
可使用ecache, 用ecache.xml構(gòu)建cacheManagerFactory降瞳,然后把factory注入實現(xiàn)cacheManager嚼鹉。
也可以使用Spring自己的基于java.util.concurrent.ConcurrentHashMap實現(xiàn)的cacheManager(該功能是從Spring3.1開始提供的)袁滥。
在service層:
然后使用@Cacheable等注解對緩存進(jìn)行操作星虹,這些注解都是org.springframework.cache提供的零抬。


參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末镊讼,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子平夜,更是在濱河造成了極大的恐慌蝶棋,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件忽妒,死亡現(xiàn)場離奇詭異玩裙,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)段直,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門吃溅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人鸯檬,你說我怎么就攤上這事决侈。” “怎么了京闰?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長甩苛。 經(jīng)常有香客問我蹂楣,道長,這世上最難降的妖魔是什么讯蒲? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任痊土,我火速辦了婚禮,結(jié)果婚禮上墨林,老公的妹妹穿的比我還像新娘赁酝。我一直安慰自己,他們只是感情好旭等,可當(dāng)我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布酌呆。 她就那樣靜靜地躺著,像睡著了一般搔耕。 火紅的嫁衣襯著肌膚如雪隙袁。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天弃榨,我揣著相機(jī)與錄音菩收,去河邊找鬼。 笑死鲸睛,一個胖子當(dāng)著我的面吹牛娜饵,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播官辈,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼箱舞,長吁一口氣:“原來是場噩夢啊……” “哼遍坟!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起褐缠,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤政鼠,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后队魏,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體公般,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年胡桨,在試婚紗的時候發(fā)現(xiàn)自己被綠了官帘。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡昧谊,死狀恐怖刽虹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情呢诬,我是刑警寧澤涌哲,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站尚镰,受9級特大地震影響阀圾,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜狗唉,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一初烘、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧分俯,春花似錦肾筐、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至杏节,卻和暖如春抓歼,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背拢锹。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工谣妻, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人卒稳。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓蹋半,卻偏偏與公主長得像,于是被迫代替她去往敵國和親充坑。 傳聞我的和親對象是個殘疾皇子减江,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容