maven+ssm整合ehcache

项目结构:


1.准备工作,也就是需要的pom文件有哪些:

        <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>
          <version>4.3.14.RELEASE</version>
        </dependency>

2.然后开始写ehcache.xml进行配置。

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <!-- java.io.tmpdir:Java临时目录。指定一个文件目录,当EhCache把数据写到硬盘上或者系统jvm内存时,将把数据写到这个文件目录下 -->
    <diskStore path="java.io.tmpdir"/>

    <!-- maxElementsInMemory:设置基于内存的缓存可存放对象的最大数目。  -->
    <!-- eternal:如果为true,表示对象永远不会过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false; -->
    <!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了 -->
    <!-- timeToIdleSeconds属性值,这个对象就会过期。当对象过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。 -->
    <!-- 如果该属性值为0,则表示对象可以无限期地处于空闲状态。  -->
    <!-- timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期。当对象过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义。  -->
    <!-- overflowToDisk:如果为true,表示当基于内存的缓存中的对象数目达到了maxElementsInMemory界限后,会把益出的对象写到基于硬盘的缓存中。 -->

    <!-- 设定缓存的默认数据过期策略 -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="10"
            timeToLiveSeconds="20"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"/>

    <!--  自定义缓存策略-学生信息缓存容器对应策略-->
    <cache name="myCache"
           maxElementsInMemory="1000"
           eternal="false"
           overflowToDisk="true"
           timeToIdleSeconds="10"
           timeToLiveSeconds="20"/>
</ehcache>

3.新建spring-ehcache.xml添加ehcache配置。

<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">


    <!--配置cache-->
    <cache:annotation-driven cache-manager="cacheManager"/>

    <!--需要引入ehcache.jar 和 spring-context-support.jar-->
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcache"/>
    </bean>
    <!-- 引入刚才的配置文件,一定要看好路径-->
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml"></property>
    </bean>
</beans>

4.然后将spring-ehcache.xml文件引入到applicationContext.xml中,保证项目启动时进行加载。

<import resource="spring-ehcache.xml"/>

5.接下来我们就开始写controller->service->dao层的逻辑。

controller层

    @Resource
    private EhcacheService ehcacheService;
     
 @RequestMapping("/find3")
 @ResponseBody
 public String findAll3() {
      ResultData rd = new ResultData(ehcacheService.findAll());
      return rd.toString();
 }

service层

public interface EhcacheService {
    List<TraLinks> findAll();
}
@Service
public class EhcacheServiceImpl implements EhcacheService

{
    @Autowired
    private TraLinksMapper traLinksMapper;

    @Override
//  @Cacheable(value="myCache")
    public List<TraLinks> findAll() {
        TraLinksExample tle = new TraLinksExample();
        TraLinksExample.Criteria criteria = tle.createCriteria();
        List<Integer> a = new ArrayList();
        a.add(1);
        criteria.andTypeIn(a);
        return traLinksMapper.selectByExample(tle);
    }
}

dao层

mapper.java

public interface TraLinksMapper {
     // @Options(useCache = true)
    List<TraLinks> selectByExample(TraLinksExample example);

}

mapper.xml

<?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.pancake.dao.TraLinksMapper" >
<resultMap id="BaseResultMap" type="com.pancake.pojo.TraLinks" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="process_id" property="processId" jdbcType="BIGINT" />
    <result column="form_id" property="formId" jdbcType="BIGINT" />
    <result column="company_id" property="companyId" jdbcType="BIGINT" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="type" property="type" jdbcType="INTEGER" />
    <result column="code_rel" property="codeRel" jdbcType="INTEGER" />
    <result column="scan_mode" property="scanMode" jdbcType="INTEGER" />
    <result column="locations_status" property="locationsStatus" jdbcType="INTEGER" />
    <result column="create_user_id" property="createUserId" jdbcType="BIGINT" />
    <result column="create_user_name" property="createUserName" jdbcType="VARCHAR" />
    <result column="create_time" property="createTime" jdbcType="CHAR" />
    <result column="update_user_id" property="updateUserId" jdbcType="BIGINT" />
    <result column="update_user_name" property="updateUserName" jdbcType="VARCHAR" />
    <result column="update_time" property="updateTime" jdbcType="CHAR" />
    <result column="code_relation" property="codeRelation" jdbcType="INTEGER" />
    <result column="scan_model" property="scanModel" jdbcType="INTEGER" />
    <result column="radius" property="radius" jdbcType="DOUBLE" />
    <result column="remark" property="remark" jdbcType="VARCHAR" />
    <result column="sub_code_num" property="subCodeNum" jdbcType="INTEGER" />
    <result column="customer_show_flag" property="customerShowFlag" jdbcType="INTEGER" />
    <result column="quality_id" property="qualityId" jdbcType="BIGINT" />
</resultMap>
<sql id="Base_Column_List" >
    id, process_id, form_id, company_id, name, type, code_rel, scan_mode, locations_status, 
    create_user_id, create_user_name, create_time, update_user_id, update_user_name, 
    update_time, code_relation, scan_model, radius, remark, sub_code_num, customer_show_flag, 
    quality_id
</sql>
<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.pancake.pojo.TraLinksExample" >
 select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from tra_links
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
</select>

6.有以下三种办法使用cache

 a.直接在service实现类相关方法上添加@Cacheable(value="myCache")

 b.在相应mapper.xml文件中添加

    
      第一种打印cache日志     
     <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
     第二种不打印cache日志
     <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
然后再在相应的<select ></seelct>标签中添加useCache=true  或者false,默认是false。

 c.在相应的mapper.java中添加@Option(useCache=true 或者false)默认false  

    以及在mapper.xml中添加    

     <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
     <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

和方法二类似,只是换成了注解,个人理解在mapper.java的方法上添加注解方便管理。

7.最后的结果


因为cache的缓存时间设置的是20秒,所以再20秒后又会重新访问数据库调用select打印sql。

欢迎大家的指正和评论。



猜你喜欢

转载自blog.csdn.net/qq_35221138/article/details/80982359