spring mvc+mybatis ehcache缓存配置

5 篇文章 0 订阅

1.下载mybatis相关包与ehcache相关包

下载地址为:https://github.com/mybatis/ehcache-cache/releases

配置文件

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">       
     <!--
	name:Cache的唯一标识
	maxElementsInMemory:内存中最大缓存对象数
	maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大
	eternal:Element是否永久有效,一但设置了,timeout将不起作用
	overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中
	timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
	timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大 
	diskPersistent:是否缓存虚拟机重启期数据
	diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒
	diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
	 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用) 
	-->
    <diskStore path="java.io.tmpdir"/>  
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />
    <!--           
    配置自定义缓存          
    maxElementsInMemory:缓存中允许创建的最大对象数          
    eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。          
    timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,                      
                    两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,                      
                    如果该值是 0 就意味着元素可以停顿无穷长的时间。          
    timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,
    如果该值是0就意味着元素可以停顿无穷长的时间。          
    overflowToDisk:内存不足时,是否启用磁盘缓存。          
    memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。      
    -->       
<!--     <cache name="testCache"           
    maxElementsInMemory="10000"           
    eternal="true"          
    overflowToDisk="false"           
    timeToIdleSeconds="0"           
    timeToLiveSeconds="600"          
    memoryStoreEvictionPolicy="LFU" />  
 -->
</ehcache>
spring.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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop ="http://www.springframework.org/schema/aop"
        xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
    <!-- 使用 annotation -->
    <context:annotation-config />
    <!-- 使用 annotation 自动注册bean,并检查@Controller, @Service, @Repository注解已被注入-->
    <context:component-scan base-package="com.ding.dao" />
	
    <!-- 引入数据库配置文件 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>classpath*:/config/data.properties</value>
        </property>
    </bean>

    <!--配置数据库连接池-->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc_driver}"/>
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />
        <property name="initialSize" value="20"/>
        <property name="minIdle" value="10"/>
        <!-- 可以在池中保持空闲的最大连接数,超出设置值之外的空闲连接将被回收,如设置为负数,则不限制 -->
        <property name="maxIdle" value="0"/>
        <!-- 可以在这个池中同时被分配的有效连接数的最大值,如设置为负数,则不限制 -->
        <property name="maxTotal" value="250"/>
        <!--最大等待秒数,单位为毫秒, 超过时间会报出错误信息-->
        <property name="maxWaitMillis" value="3600"/>
        <!-- 自我中断,默认是false-->
        <property name="removeAbandonedOnBorrow" value="true" />
        <!-- 一个被抛弃连接可以被移除的超时时间,单位为秒 ,连接回收-->
        <property name="removeAbandonedTimeout" value="300"/>
    </bean>

    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- mybatis xml的dao配置方式 -->
        <property name="mapperLocations" value="classpath:com/ding/mapper/*mapper.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ding.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
    </bean>
    
    
    <!-- 缓存配置(两种) -->  
    <!-- 启用缓存注解功能(请将其配置在Spring主配置文件中) -->  
    <cache:annotation-driven cache-manager="cacheManager"/>  
    <!-- Spring自己的基于java.util.concurrent.ConcurrentHashMap实现的缓存管理器(该功能是从Spring3.1开始提供的) -->  
    <!--   
    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">  
        <property name="caches">  
            <set>  
                <bean name="myCache" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"/>  
            </set>  
        </property>  
    </bean>  
     -->  
    <!-- 若只想使用Spring自身提供的缓存器,则注释掉下面的两个关于Ehcache配置的bean,并启用上面的SimpleCacheManager即可 -->  
    <!-- Spring提供的基于的Ehcache实现的缓存管理器 -->  
    <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
        <property name="configLocation" value="classpath:/config/ehcache.xml"/>  
        <property name="shared" value="true" />
    </bean>  
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">  
        <property name="cacheManager" ref="cacheManagerFactory"/>  
    </bean> 
    
    
    <!--开启事务驱动-->
    <tx:annotation-driven/>
    <!-- 事务的配置 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 事务传播规则 -->
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 配置AOP (把切面点与事务通知关联形成一个切面) -->
    <aop:config>
        <aop:pointcut expression="execution (* com.*.service.*.*(..))"  id="txPointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
    </aop:config>

</beans>
dao类 mybatis :user_mapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
<mapper namespace="com.ding.dao.UserDao">   
    <!--mybatis ehcache缓存配置 -->
    <!-- 以下两个<cache>标签二选一,第一个可以输出日志,第二个不输出日志 -->
   <!--  <cache type="org.mybatis.caches.ehcache.LoggingEhcache" /> -->
   <cache type="org.mybatis.caches.ehcache.EhcacheCache" >  
    <property name="timeToIdleSeconds" value="3600"/><!--1 hour-->  
    <property name="timeToLiveSeconds" value="3600"/><!--1 hour-->  
    <property name="maxEntriesLocalHeap" value="1000"/>  
    <property name="maxEntriesLocalDisk" value="10000000"/>  
    <property name="memoryStoreEvictionPolicy" value="LRU"/>  
</cache> 
    <!--结果集-->
    <resultMap id="userMap" type="com.ding.pojo.User">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="password" column="password"/>
        <result property="age" column="age"/>
    </resultMap>
    
    <!-- 查询所有的用户数据,ID和dao中的方法对应 -->
    <select id="findAll" resultMap="userMap">
        SELECT * FROM user
    </select>
	<!--  统计user表的总条数 -->
    <select id="findCount" resultType="int">
        select count(*) from user
    </select>
    <!-- 新增用户信息 -->
    <insert  id="addUser" parameterType="com.ding.pojo.User" useGeneratedKeys="true" keyProperty="id">
        insert into user(id,name,password,age) values(#{id},#{name},#{password},#{age})
    </insert>
    <!-- 修改数据 -->
    <update id = "modifyUser" parameterType="com.ding.pojo.User" >
        update user set name=#{name},password = #{password},age =#{age} where id =#{id}
    </update>
    
     <!-- 删除数据 -->
    <update id = "deleteUser" parameterType="int" >
      	delete from user where id=#{id}
    </update>
    <!-- 根据ID查找数据 -->
    <select id="findById" parameterType="int" resultMap="userMap">
        select * from user where id =#{id}
    </select>
</mapper>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <display-name>springMVC-mybatis</display-name>
    <filter>
        <filter-name>encodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath*:/config/log4j.properties</param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/config/spring-mybatis.xml</param-value>
    </context-param>
    <!--spring 监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>springMVCDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 初始化加载spring mvc配置文件的位置 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:/config/springMVC-servlet.xml</param-value>
        </init-param>
        <!--延时加载时间-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVCDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

本次做测试:正常查询数据10条不加缓存,浏览器响应大概需要15-30s,加缓后响应时间平均大概0-4s之间.



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值