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


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

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

首先配置EhCache jar包

<!-- 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>

目錄結構

配置ehcache-setting.xml

<?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配置相關信息

<?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"):在查詢時,會先在緩存中查找數據,當緩存中數據不存在時,才會執行之后方法查找數據庫

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

然后啟動tomcat,輸入網址 http://localhost:8080/ssm/student/selectstudentbyid?id=1

 

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

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

 

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

 

接下來我們測試更新

這是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作緩存數據庫


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM