緩存初解(五)---SpringMVC基于注解的緩存配置--web應用實例

之前為大家介紹了如何使用spring注解來進行緩存配置 (EHCache 和 OSCache)的簡單的例子,詳見

Spring基于注解的緩存配置--EHCache?AND OSCache

現在介紹一下如何在基于注解springMVC的web應用中使用注解緩存,其實很簡單,就是將springMVC配置文件與緩存注解文件一起聲明到context中就OK了。

下面我就來構建一個基于spring注解小型的web應用,這里我使用EHCache來作為緩存方案

jar依賴:

ehcache-core-1.7.2.jar
jakarta-oro-2.0.8.jar
slf4j-api-1.5.8.jar
slf4j-jdk14-1.5.8.jar?
cglib-nodep-2.1_3.jar
commons-logging.jar
log4j-1.2.15.jar
spring-modules-cache.jar
spring.jar?
jstl.jar

standard.jar

接著我們來編寫web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"id="WebApp_ID" version="2.4"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><display-name>SpringCacheWeb</display-name><!-- 由spring加載log4j --><context-param><param-name>log4jConfigLocation</param-name><param-value>classpath:log4j.properties</param-value></context-param><!-- 聲明spring配置文件 --><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/spring-servlet.xml</param-value></context-param><!-- 使用UTF-8編碼 --><filter><filter-name>Set Character Encoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>Set Character Encoding</filter-name><url-pattern>*.do</url-pattern></filter-mapping><!-- 負責初始化log4j--><listener><listener-class>org.springframework.web.util.Log4jConfigListener</listener-class></listener><!-- 負責初始化spring上下文--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- springMVC控制器--><servlet><servlet-name>spring</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>spring</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping><session-config><session-timeout>10</session-timeout></session-config><welcome-file-list><welcome-file>index.jsp</welcome-file><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file></welcome-file-list>
</web-app>

?接著我們來編寫spring-servlet.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:context="http://www.springframework.org/schema/context"xmlns:ehcache="http://www.springmodules.org/schema/ehcache"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd"default-lazy-init="true"><!--啟用注解   定義組件查找規則 --><context:component-scan base-package="com.netqin"><context:include-filter type="annotation"expression="org.springframework.stereotype.Controller" /><context:include-filter type="annotation"expression="org.springframework.stereotype.Service" /><context:include-filter type="annotation"expression="org.springframework.stereotype.Repository" /></context:component-scan><!-- 視圖查找器 --><bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass"value="org.springframework.web.servlet.view.JstlView"></property><property name="prefix" value="/WEB-INF/jsp/"></property><property name="suffix" value=".jsp"></property></bean><!-- 加載ehcache緩存配置文件 說明:在這里我遇到了這樣一個問題,當使用@Service等注解的方式將類聲明到配置文件中時,就需要將緩存配置import到主配置文件中,否則緩存會不起作用如果是通過<bean>聲明到配置文件中時,則只需要在web.xml的contextConfigLocation中加入applicationContext-ehcache.xml即可,不過還是推薦使用如下方式吧,因為這樣不會有任何問題--><import resource="classpath:applicationContext-ehcache.xml"/>
</beans>

?

ok,我們接著編寫applicationContext-ehcache.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:ehcache="http://www.springmodules.org/schema/ehcache"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd"><ehcache:config configLocation="classpath:ehcache.xml"id="cacheProvider" /><ehcache:annotations providerId="cacheProvider"><ehcache:caching cacheName="testCache" id="testCaching" /><ehcache:flushing cacheNames="testCache" id="testFlushing" /></ehcache:annotations></beans>

?ehcache.xml如下

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"monitoring="autodetect"><diskStore path="java.io.tmpdir"/><defaultCachemaxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true"maxElementsOnDisk="10000000"diskPersistent="false"diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"/><cache name="testCache"maxElementsInMemory="10000"maxElementsOnDisk="1000"eternal="false"overflowToDisk="true"diskSpoolBufferSizeMB="20"timeToIdleSeconds="300"timeToLiveSeconds="600"memoryStoreEvictionPolicy="LFU"/>
</ehcache>

?

ok,配置文件都完成了,接著我們來編寫controller、service和dao

1.CacheDemoController:

package com.netqin.function.cacheDemo;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
public class CacheDemoController {@Autowiredprivate CacheDemoService service;@RequestMapping("/demo.do")public String handleIndex(Model model) {System.out.println(service.getName(0));model.addAttribute("name", service.getName(0));return "cacheDemo";}@RequestMapping("/demoFulsh.do")public String handleFulsh(Model model) {service.flush();return "cacheDemo";}
}

?2.CacheDemoService :

package com.netqin.function.cacheDemo;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springmodules.cache.annotations.CacheFlush;
import org.springmodules.cache.annotations.Cacheable;@Service
public class CacheDemoService {@Autowiredprivate CacheDemoDao dao;@Cacheable(modelId = "testCaching")public String getName(int id){System.out.println("Processing testCaching");return dao.getName(id);}@CacheFlush(modelId = "testFlushing")public void flush(){System.out.println("Processing testFlushing");}}

?

我們只對service層加入了注解緩存配置。

?

接著我們來寫一個簡單的頁面,cacheDemo.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
CacheDemo:${name}
</body>
</html>

?

ok,一切就緒,我們啟動服務器,并訪問http://localhost:8080/cache/demo.do

?

多請求幾次,請求兩次的輸出結果:

Processing testCaching
NameId:0
NameId:0

?

說明緩存起作用了,ok!

?

接著我們刷新該緩存,訪問http://localhost:8080/cache/demoFulsh.do

再請求http://localhost:8080/cache/demo.do

輸出結果:

Processing testCaching
NameId:0
NameId:0
Processing testFlushing
Processing testCaching
NameId:0

?

緩存刷新成功。

轉載于:https://www.cnblogs.com/wcyBlog/p/3949709.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273604.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273604.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273604.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Redis String 類型操作及常用命令

七個原則 Redis 是一個操作數據結構的語言工具&#xff0c;它提供基于 TCP 的協議以操作豐富的數據結構。在 Redis 中&#xff0c;數據結構這個詞的意義不僅表示在某種數據結構上的操作&#xff0c;更包括了結構本身及這些操作的時間空間復雜度。Redis 定位于一個內存數據庫&am…

于我,過去,現在和未來 —— 西格里夫·薩松

In me, past, present, future meet            于我&#xff0c;過去、現在和未來To hold long chiding conference              商討聚會 各執一詞 紛擾不息My lusts usurp the present tense             林林總總的 欲望&#xff0c;…

Java assert關鍵字

Java assert關鍵字 Assert 簡介 Java2在1.4中新增了一個關鍵字&#xff1a;assert。在程序開發過程中使用它創建一個斷言(assertion)。語法格式有兩種&#xff1a; assert condition; 這里condition是一個必須為真(true)的表達式。如果表達式的結果為true&#xff0c;那么斷言為…

linux 二級域名設置

首先&#xff0c;你的擁有一個有泛域名解析的頂級域名&#xff0c;例如&#xff1a; domain.com  其次&#xff0c;在 httpd.conf 中打開 mod_rewrite  之后&#xff0c;在 httpd.conf 的最后&#xff0c;添加以下內容&#xff1a;  RewriteEngine on  RewriteMap lowe…

Spring Boot @Conditional 注解

Spring Boot Conditional注解 Conditional是Spring4新提供的注解&#xff0c;它的作用是按照一定的條件進行判斷&#xff0c;滿足條件的才給容器注冊Bean。 Conditional注解定義 Target({ElementType.TYPE, ElementType.METHOD}) Retention(RetentionPolicy.RUNTIME) Documente…

計算幾何 半平面交

LA 4992 && hdu 3761 Jungle Outpost 杭電的有點坑啊。。一直爆內存&#xff0c;后來發現大白的半平面交模板那里 point *p new point[n]; line *q new line[n]這里出了問題&#xff0c;應該是在函數里面申請不了比較大的數組&#xff0c;所以爆內存。。我在全局定義…

Maven 強制導入jar包

場景 有時候因為各種原因(依賴有了&#xff0c;jar包有了)&#xff0c;項目中就是沒有這個jar包。 在需要強導的項目中創建lib文件夾&#xff0c;將需要強導的jar包訪問lib中。添加依賴$&#xff5b;pom.basedir&#xff5d;:獲取當前所在的項目目錄 $&#xff5b;pom.basedir&…

0910

我累得時候希望你能在我身邊&#xff0c;在你的懷里好好的睡一覺。轉載于:https://www.cnblogs.com/zhanzhao/p/3964175.html

《Java 高并發》03 線程的生命周期

相關概念 進程是指一個內存中運行的應用程序&#xff0c;每個進程都有自己獨立的一塊內存空間&#xff0c;一個進程中可以啟動多個線程。 一個進程是一個獨立的運行環境&#xff0c;它可以被看作一個程序或者一個應用。而線程是在進程中執行的一個任務。Java運行環境是一個包含…

OpenLayers3 online build

openlayers3使用了一個比較復雜的build工具&#xff0c;從github上下載下來的代碼中并沒有build之后的版本&#xff0c;要配置build環境又比較繁瑣&#xff0c;好在官方的example中提供了在線的版本&#xff0c;下面就是link&#xff1a; http://openlayers.org/en/v3.0.0/buil…

Mysql 必知必會(一)

文章案例所需的SQL文件&#xff0c;點擊下載 使用MySQL 進入mysql安裝目錄下的bin目錄&#xff1a; 連接Mysql&#xff1a;mysql -uroot -p123456;顯示Mysql下的所有數據庫&#xff1a;show databases;切換數據庫&#xff1a;use local;顯示數據庫下所有表名&#xff1a;show t…

design.js

//模塊式開發 var myNamespace (function () { var myPrivateVar 0;var myPrivateMethod function (foo) {console.log(foo); };return {myPublicVar : "foo",myPublicFunction : function (bar) {myPrivateVar;myPrivateMethod(bar);} }; })(); //原型模式 var…

Spring boot 整合dynamic實現多數據源

項目git地址&#xff1a;Jacob-dynamic 準備工作 # 創建數據庫db1 CREATE DATABASE db1CHARACTER SET utf8 COLLATE utf8_bin # 創建user表 CREATE TABLE user (id int(11) DEFAULT NULL,name varchar(255) DEFAULT NULL ) ENGINEInnoDB DEFAULT CHARSETutf8 # 添加數據 INSERT…

LInux 命令大全

開關機 reboot&#xff1a;重啟shutdown -h 0 或者init 0 &#xff1a;關機halt&#xff1a;關機poweroff:關機 文件的操作 ll&#xff1a;顯示文件夾詳細信息ls&#xff1a;顯示文件目錄mkdir fileName&#xff1a;創建目錄mkdir -p fileName/fileName&#xff1a;目錄cd file…

企業級業務系統開發實戰-序言

前些年一直在做微軟的解決方案實施與軟件開發的工作。在學習、項目實施、開發與管理的過程中學到了別人不少好的東西&#xff0c;也自身總結了大量的經驗&#xff0c;希望能夠通過一個系列來跟大家分享關于軟件開發方面的內容。 這個開發系列的由來是這樣的&#xff0c;兩年前作…

Could not autowire. No beans of 'JavaMailSender' type found..md

Could not autowire. No beans of JavaMailSender type found. 導入依賴 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId><version>2.1.5.RELEASE</version> </depe…

極客Web前端開發資源集錦

本周我們帶來的前端推薦包含當前熱門的bootstrap&#xff0c;html5&#xff0c;css3等技術內容和新聞話題&#xff0c;如果你還想近一步學習如何開發&#xff0c;還可以關注我們的極客課程庫&#xff0c;里面涵蓋了現代開發技術的‘學’與‘習’的全新功能。希望對大家有所幫助…

mahout學習筆記4

分析數據 有哪些數據 選用什么樣的推薦算法 Finding an effective recommender 各種算法組合測試 Tanimoto算法在與thresholdneighborhoold結合時值應該設置比較底&#xff0c;0.5已經是很高的相似度 可以重寫ItemSimilarity &#xff0c;把自己的功能放到里面 IDRescorer 可以…

使用 Spring Cloud 實現微服務系統

使用 Spring Cloud 實現微服務系統 準備工作&#xff1a;為了方便創建項目&#xff0c;以及各版本以來關系&#xff0c;此次創建項目使用 Spring Assistant插件。 創建單體服務中心項目 啟用服務端的服務注冊&#xff0c;發現功能 EnableEurekaServer SpringBootApplication pu…

HTML+CSS公司培訓(一)高手請飄過

隨著公司的轉向&#xff0c;從.net到webapp很多人無從適應。因此在公司進行一些簡單的培訓。同時把我微薄的經驗分享給大家&#xff0c;并且和大家一起學習進步。 對于HTML在正常的開發中我們其實用的標簽就是那么簡單的幾個&#xff08;是小編在項目開發中常用的一些&#xff…