Ssm+ehcache SSM Simple Integration Ehcache cache

Source: Internet
Author: User
Tags aop stub

Z Here only SSM integrated Ehcache cache, for children who do not know the SSM, please first browse the SSM integration

EhCache is a pure Java in-process caching framework, which is fast and capable, and is the default Cacheprovider in Hibernate. Ehcache is a widely used, open source Java distributed cache. Primarily for general purpose caches, Java EE and lightweight containers. It features memory and disk storage, cache loaders, cache extensions, cache exception handlers, a gzip cache servlet filter, and support for rest and soap APIs.

First configure the Ehcache jar package

<!--Ehcache Dependent        -<!--https://Mvnrepository.com/artifact/net.sf.ehcache/ehcache-- >        <dependency>            <groupId>net.sf.ehcache</groupId>            <artifactId> ehcache</artifactid>            <version>2.10.4</version>        </dependency>        < dependency>            <groupId>org.springframework</groupId>            <artifactId> spring-context-support</artifactid>        </dependency>    </dependencies>

Directory structure

Configure Ehcache-setting.xml

<?xml version= "1.0" encoding= "UTF-8"?><ehcache> <!--Specify a file directory that will be written to this file directory when Ehcache writes the data to the hard drive. <diskstore path= "F:\cache\java-cache"/> <!--set the default data expiration policy for the cache--<Defaultcache maxelementsinmemory= "10000"Eternal= "false"Overflowtodisk= "true"Timetoidleseconds= "10"Timetoliveseconds= "20"diskpersistent= "false"Diskexpirythreadintervalseconds= "/>" <cache name= "Cachetest"maxelementsinmemory= "1000"Eternal= "false"Overflowtodisk= "true"Timetoidleseconds= "100"Timetoliveseconds= "/></ehcache>"

Add Ehcache configuration related information in Applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"Xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:p= "http://www.springframework.org/schema/p"Xmlns:util= "Http://www.springframework.org/schema/util" xmlns:jdbc= "Http://www.springframework.org/schema/jdbc"Xmlns:cache= "Http://www.springframework.org/schema/cache"xsi:schemalocation= "http://Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context.xsdhttp//Www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans.xsdhttp//Www.springframework.org/schema/txhttp//www.springframework.org/schema/tx/spring-tx.xsdhttp//Www.springframework.org/schema/jdbchttp//www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsdhttp//Www.springframework.org/schema/cachehttp//www.springframework.org/schema/cache/spring-cache-3.1.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp//www.springframework.org/schema/aop/spring-aop.xsdhttp//Www.springframework.org/schema/utilhttp//www.springframework.org/schema/util/spring-util.xsd "><!--annotations Scan-<context:component-scan base- Package= "com.test.*" ></context:component-scan> <!--apply Spring cache annotation Function--<cache:annotation-driven C ache-manager= "CacheManager"/> <!--loading db.properties file contents--<context:property-placeholder location= "cl Asspath:db.properties "/> <!--configuration data source, DBPC-<bean id=" Datasourse "class= "Org.apache.commons.dbcp.BasicDataSource" > <property name= "driverclassname" value= "${jdbc.driver}" >< /property> <property name= "url" value= "${jdbc.url}" ></property> <property name= "username" Value= "${jdbc.username}" ></property> <property name= "password" value= "${jdbc.password}" ></ Property> </bean> <!--sqlsessionfactory--<bean id= "Sqlsessionfactory"class= "Org.mybatis.spring.SqlSessionFactoryBean" > <!--database connection pool--<property name= "DataSource" ref= "da Tasourse "></property> <!--load Mybtis Global profile--<property name=" Configlocation "value=" class Path:mybaties-config.xml "></property> </bean> <!--mapper Scanner--<beanclass= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name= "basepackage" value= "Com.test.mapper" &    gt;</property> <property name= "Sqlsessionfactorybeanname" value= "Sqlsessionfactory" ></property> </bean> <!--transaction management: Datasourcetransactionmanager DataSource: Referencing the data source defined above--<bean id= "Txmanager"class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name= "DataSource" ref= " Datasourse "></property> </bean> <!--use declarative transaction Transaction-manager: Reference the transaction manager defined above--<tx:ann Otation-driven transaction-manager= "Txmanager"/> <Beanclass= "Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" > <property name= "            Messageconverters "> <list> <ref bean=" Mappingjackson2httpmessageconverter "/> </list> </property> </bean> <bean id= "Mappingjackson2httpmessageconverter"class= "Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" > <property name= "                Supportedmediatypes "> <list> <value>text/html;charset=UTF-8</value> <value>text/json;charset=UTF-8</value> <value>application/json;charset=utf-8</ value> </list> </property> </bean> <!--configuration Ehcache Manager-<bean id= "CacheManager"class= "Org.springframework.cache.ehcache.EhCacheCacheManager" > <property name= "CacheManager" ref= "Ehcache" &GT;&L t;/property> </bean> <bean id= "Ehcache"class= "Org.springframework.cache.ehcache.EhCacheManagerFactoryBean" > <property name= "configlocation" value= "Clas Spath:ehcache-setting.xml "></property> </bean> </beans>

Add Ehcache related annotations to the service

 PackageCom.test.service;Importjava.util.List;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.cache.annotation.CacheEvict;Importorg.springframework.cache.annotation.Cacheable;ImportOrg.springframework.stereotype.Service;Importorg.springframework.transaction.annotation.Transactional;ImportCom.test.mapper.StudentMapper;Importcom.test.model.Student;/** *  * @authorZZ **/@Service @transactional (rollbackfor=exception.class) Public classScserviceimplImplementsscservice{@Autowired studentmapper studentmapper; @Override @Cacheable (Value= "Cachetest")     PublicStudent Selectstudentbyid (intSID) {        //TODO auto-generated Method Stub                returnStudentmapper.selectstudentbyid (SID); } @Override @CacheEvict (value= "Cachetest", allentries=true)     Public voidupdatestudent (Student Student) {//TODO auto-generated Method Stubstudentmapper.updatestudent (student); }            }

where @Cacheable (value= "Cachetest"): When querying, the data is first found in the cache, and when the data in the cache does not exist, the method is then executed to find the database

@CacheEvict (value= "Cachetest", Allentries=true): In order to ensure the consistency of cache and database information, the cache information will be emptied when performing additions and deletions.

Then launch tomcat and enter the URL http://localhost:8080/ssm/student/selectstudentbyid?id=1

When the first access, the cache has no data, it will go to the database to find.

We'll refresh the URL once again.

As we can see, the second access does not fetch the data from the database, but rather the direct access to the cache (it is not possible to see the running time ratio)

Next we test the update

Here is the controller code:

 PackageCom.test.controller;Importorg.springframework.web.bind.annotation.RequestMapping;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;ImportOrg.springframework.validation.BindingResult;Importcom.test.model.Student;ImportCom.test.service.ScService;/** *  * @authorZZ **/@Controller @requestmapping ("/student") Public classStudentcontroller {@Autowired scservice scservice; @RequestMapping ("/selectstudentbyid")     PublicString Selectstudentbyid (model model,intID) {System.out.println (ID); Student Student=NewStudent (); Student=Scservice.selectstudentbyid (ID); Model.addattribute ("Student", student);        SYSTEM.OUT.PRINTLN (student); return"Showstudent"; } @RequestMapping ("/updatestudent")     PublicString Updatestudent (intSid,string Sname,intAge ) {Student Student=NewStudent ();        Student.setsid (SID);        Student.setsname (sname);        Student.setage (age);        Scservice.updatestudent (student); return"Redirect:/student/selectstudentbyid?id=" +SID; }}

and DAO (Mapper) and Mapper.xml.

 PackageCom.test.mapper;Importcom.test.model.Student;/** *  * @authorZZ **/ Public InterfaceStudentmapper {/*** Select Student Byid *@paramSID *@returnStudent * Query Student information based on SID*/Student Selectstudentbyid (intSID); /**     *      * @paramStudent*/    voidupdatestudent (Student Student); }

<?xml version= "1.0" encoding= "UTF-8"?> <!  DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en"  "HTTP://MYBATIS.ORG/DTD/MYBATIS-3-MAPPER.DTD" > <mapper namespace= "Com.test.mapper.StudentMapper" >    <resultmap type= "Student" id= "Studentbean" >        <id column= "id" property= "sid"/>        <result column= "name" property= "sname"/>        <result Column= "Age" property= "age"/>    </resultMap>    <select id= "Selectstudentbyid" resultmap= " Studentbean ">        * from        Student s where s.id=#{sid}    </select >    <update id= "updatestudent" parametertype= "Student" >        update Student set name=#{sname },AGE=#{SID} where id=#{sid}    </update></mapper>

Input URL: http://localhost:8080/ssm/student/updatestudent?sid=1&sname=tom&age=32

Update database information and clear cache

The database is accessed when queried because the cached data is emptied

Re-enter the URL http://localhost:8080/ssm/student/selectstudentbyid?id=1

Since the last query was written to the cache, this is read directly from the cache

Finish, next time. Use Redis as a cache database

Ssm+ehcache SSM Simple Integration Ehcache cache

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.