項目結構:
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"/>
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。
歡迎大家的指正和評論。