Spring Annotations-based cache configuration--web Application instance __spring

Source: Internet
Author: User
Tags flush log4j

Here's a simple example of how to use the spring annotations for caching configuration (EHCache and Oscache), as described in

Spring annotations based cache configuration--ehcache and Oscache

Now, how to use the annotation cache in the annotated SPRINGMVC Web application is very simple, that is, it is OK to declare the SPRINGMVC configuration file with the cached annotation file in the context.

Now I'm going to build a small Web application based on spring annotations, where I use Ehcache as a caching scheme.

First look at the directory structure, as follows:

Jar dependencies:

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

And then we'll write 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/ Java http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "> <display-name>springcacheweb</display-name > <!--loaded by spring log4j--> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <!--declaring the spring configuration file-- > <context-param> <param-name>contextConfigLocation</param-name> <param-value>/web-inf /spring-servlet.xml </param-value> </context-param> <!--using UTF-8 encoding--> <filter> < Filter-name>set Character encoding</filter-name> <filter-class> Org.springframework.web.filter.characterencodingfilter</filter-class> <init-param> <param-name >encoding</param-name&gT <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> <!--is responsible for initializing log4j--> <listener> <listener-class> Org.springframework.web.util.log4jconfiglistener</listener-class> </listener> <!-- Responsible for initializing spring context--> <listener> <listener-class> Org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!-- SPRINGMVC controller--> <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>

And then we'll write Spring-servlet.xml.

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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.xsd http://www.springframework.org/ Schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springmodules.org /schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd "default-lazy-init=" true " > <!--Enable note Definition component lookup rules--> <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> <!--view Finder --> <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> <!--loading Ehcache Cache profile Description: Here I have a problem where when you declare a class in a configuration file using annotations such as @service, The cache configuration will need to be import into the primary configuration file, otherwise the cache will not work if it is declared through <bean> to the configuration file, You only need to add applicationcontext-ehcache.xml to the contextconfiglocation of Web.xml, but it is recommended that you use the following method, because there is no problem--> < Import resource= "Classpath:applicationcontext-ehcache.xml"/> </beans>

OK, let's go ahead and write Applicationcontext-ehcache.xml, remember the namespace-based configuration described earlier, as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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.xsd Http://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 is as follows:

<?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 "/> <defaultcache maxelementsinmemory= 10000" eternal= "false" timetoidleseconds= "120" timetoliveseconds= "overflowtodisk=" "true" maxelementsondisk= "10000000" diskpersistent= "false" diskexpirythreadintervalseconds= "memorystoreevictionpolicy=" "LRU"/> <cache name= "TestCache" Maxelementsinmemory= "10000" maxelementsondisk= "1000" eternal= "false" overflowtodisk= "true" diskspoolbuffersizemb= " "Timetoidleseconds=" "timetoliveseconds=" memorystoreevictionpolicy= "LFU"/> </ehcache>

OK, the configuration files are complete, and then we'll write controller, service, and 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 {@Autowired private 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 {@Autowired private Cachedemodao dao; @Cacheable (modelid = "testcaching") public S Tring getName (int id) {System.out.println ("Processing testcaching"); return Dao.getname (ID);} @CacheFlush (ModelID = " Testflushing ") public void Flush () {System.out.println (" Processing testflushing ");}

We only add the annotation cache configuration to the service layer.

Then we'll write a simple page, 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" >

OK, all ready, we start the server, and access http://localhost:8080/cache/demo.do

Multiple requests, requests two times output result:

Processing testcaching
nameid:0
nameid:0

Description The cache is working, OK.

Then we refresh the cache and access the Http://localhost:8080/cache/demoFulsh.do

Ask Http://localhost:8080/cache/demo.do again.

Output results:

Processing testcaching
nameid:0
nameid:0
Processing testflushing
Processing testcaching
nameid:0

Cache Flush succeeded. Springcacheweb.rar (4.2 MB)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.