Spring+SpringMvc+Mybatis+ehcache ssm簡單整合ehcache緩存

z這裏只講ssm整合ehcache緩存,對於還不瞭解ssm的童鞋,請先瀏覽ssm整合那篇html

EhCache 是一個純Java的進程內緩存框架,具備快速、精幹等特色,是Hibernate中默認的CacheProvider。Ehcache是一種普遍使用的開源Java分佈式緩存。主要面向通用緩存,Java EE和輕量級容器。它具備內存和磁盤存儲,緩存加載器,緩存擴展,緩存異常處理程序,一個gzip緩存servlet過濾器,支持REST和SOAP api等特色。java

首先配置EhCache jar包web

<!-- ehcache 相關依賴 -->
        <!-- 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>

目錄結構redis

配置ehcache-setting.xmlspring

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <!-- 指定一個文件目錄,當EhCache把數據寫到硬盤上時,將把數據寫到這個文件目錄下 -->
    <diskStore path="F:\cache\java-cache"/>

    <!-- 設定緩存的默認數據過時策略 -->
    <defaultCache maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="10" timeToLiveSeconds="20" diskPersistent="false" diskExpiryThreadIntervalSeconds="120"/>

    <cache name="cacheTest" maxElementsInMemory="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="100" timeToLiveSeconds="200"/>

</ehcache>

在applicationContext.xml里加入ehcache配置相關信息sql

<?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/context 
    http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/jdbc 
    http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd 
    http://www.springframework.org/schema/cache 
    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">
    <!-- 註解掃描 -->
    <context:component-scan base-package="com.test.*"></context:component-scan>
    <!-- 應用spring cache註解功能  -->  
     <cache:annotation-driven cache-manager="cacheManager" />  
    <!-- 加載db.properties文件內容 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 配置數據源,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">
        <!-- 數據庫鏈接池 -->
        <property name="dataSource" ref="dataSourse"></property>
        <!-- 加載mybtis全局配置文件 -->
        <property name="configLocation" value="classpath:mybaties-config.xml"></property>
    </bean>
    <!-- mapper掃描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.test.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- 事務管理 : DataSourceTransactionManager dataSource:引用上面定義的數據源 -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSourse"></property>
    </bean>

    <!-- 使用聲明式事務 transaction-manager:引用上面定義的事務管理器 -->
    <tx:annotation-driven transaction-manager="txManager" />

    <bean class="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>

    <!-- 配置ehcache管理器-->

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">  
        <property name="cacheManager" ref="ehcache"></property>  
    </bean>  

    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
        <property name="configLocation" value="classpath:ehcache-setting.xml"></property>  
    </bean>  
</beans>

在Service中加入Ehcache相關注解數據庫

package com.test.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.test.mapper.StudentMapper; import com.test.model.Student; /** * * @author zz * */ @Service @Transactional(rollbackFor=Exception.class) public class ScServiceImpl implements ScService{ @Autowired StudentMapper studentMapper; @Override @Cacheable(value="cacheTest") public Student selectStudentByID(int sid) { // TODO Auto-generated method stub
        
        return studentMapper.selectStudentByID(sid); } @Override @CacheEvict(value="cacheTest",allEntries=true) public void updateStudent(Student student) { // TODO Auto-generated method stub
 studentMapper.updateStudent(student); } }

其中,@Cacheable(value="cacheTest"):在查詢時,會先在緩存中查找數據,當緩存中數據不存在時,纔會執行以後方法查找數據庫apache

@CacheEvict(value="cacheTest",allEntries=true):在執行增刪改操做時,爲了保證緩存和數據庫信息一致性,會將緩存信息清空。json

而後啓動tomcat,輸入網址 http://localhost:8080/ssm/student/selectstudentbyid?id=1api

 

當第一次訪問時,緩存沒有數據,就會去數據庫中查找。

咱們再刷新一次剛剛的網址

 

咱們能夠看出,第二次訪問沒用從數據庫取數據,而是直接訪問緩存(不信能夠看運行時間比對)

 

接下來咱們測試更新

這是controller代碼:

package com.test.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import com.test.model.Student; import com.test.service.ScService; /** * * @author zz * */ @Controller @RequestMapping("/student") public class StudentController { @Autowired ScService scService; @RequestMapping("/selectstudentbyid") public String selectstudentbyid(Model model, int id) { System.out.println(id); Student student = new Student(); student = scService.selectStudentByID(id); model.addAttribute("student", student); System.out.println(student); return "showstudent"; } @RequestMapping("/updatestudent") public String updateStudent(int sid,String sname,int age) { Student student=new Student(); student.setSid(sid); student.setSname(sname); student.setAge(age); scService.updateStudent(student); return "redirect:/student/selectstudentbyid?id="+sid; } }

還有dao(mapper)的和mapper.xml

package com.test.mapper; import com.test.model.Student; /** * * @author zz * */
public interface StudentMapper { /** * select Student ByID * @param sid * @return student * 根據sid查詢學生信息 */ Student selectStudentByID(int sid); /** * * @param student */
    void updateStudent(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"> select * 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>

 

輸入網址:http://localhost:8080/ssm/student/updatestudent?sid=1&sname=tom&age=32

 

 更新數據庫信息而且清除緩存

因爲緩存數據被清空,因此查詢時又訪問數據庫

再次輸入網址 http://localhost:8080/ssm/student/selectstudentbyid?id=1

因爲上次查詢時寫入緩存,因此這次直接從緩存中讀取

完畢,下次再寫篇利用redis做緩存數據庫

相關文章
相關標籤/搜索