要实现基于注解的缓存实现,要求Spring的版本在3.1或以上版本。

首先需要在spring的配置文件中添加对缓存注解的实现:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
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.xsd"> <context:component-scan base-package="com.xxx" /> <!-- 启用缓存注解功能 -->
<cache:annotation-driven cache-manager="ehcacheManager"/>
<bean id="ehcacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean>
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcacheManagerFactory" />
</bean> </beans>

ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<diskStore path="java.io.tmpdir" />
<defaultCache name="defaultCache" maxElementsInMemory="300" timeToLiveSeconds="1800"
eternal="false" overflowToDisk="true" /> <cache name="springCache" maxElementsInMemory="300" timeToLiveSeconds="1800"
eternal="false" overflowToDisk="true"/>
</ehcache>

注解的使用:

@Service
public class MyServiceImpl implements MyService {
......
@Cacheable(value="springCache",key="'userlist_' + #param['username']")
public List<Map<String, Object>> queryUserList(Map<String, Object> param)
throws Exception {
return userDAO.queryUserList(param);
}
......
}

  添加了@Cacheable的注解,value属性设为固定值springCache,该值对应ehcache.xml文件中cache的name,key属性设为缓存的名称,可以是一个固定值,比如’userlist’,也可以添加上请求方法的属性值,比如’userlist_’ + #param[‘username’],用于确保输入参数不同,输出的值不同的情况。

  除了@Cacheable注解,还有@CachePut@CacheEvict两个注解,区别在于:

  @Cacheable:如果使用@Cacheable注解,先检查对应的缓存是否存在,如果缓存存在,直接取缓存值返回,不再执行方法体内容;如果缓存不存在,则执行方法体内容,并且将返回的内容写入缓存
  @CachePut:使用@CachePut注解和@Cacheable注解类似,只是不管对应缓存是否存在,都执行方法体,并且将返回的内容写入缓存
  @CacheEvict:@CacheEvict注解表示对应缓存的删除

缓存的使用总结:

  在读取数据时,使用@Cacheable注解将数据加入缓存
  在数据发生改变时,使用@CachePut注解更新缓存
  在数据被删除时,使用@CacheEvict注解删除缓存

最新文章

  1. centos 20T硬盘(超过16T)分区
  2. Linq专题之集合初始化器
  3. Oracle数据库语句大全
  4. 寻找代表元(codevs 2776)
  5. node基础 --全局
  6. GUID
  7. LCD驱动 15 -2
  8. log4net自定义字段写入SqlServer数据库 ASP.net
  9. IE 6/7下自赋值导致 overflow 溢出
  10. CSAPP:cachelab(1)
  11. Latch-up 閂鎖效應 &amp; 靜電放電模式
  12. P1316 丢瓶盖--(二分答案)
  13. ubuntu16.10安装网易云音乐
  14. matlib实现梯度下降法
  15. html的a标签的 href 和 onclick。
  16. Bootstrap组件系列之福利篇几款好用的组件(推荐)
  17. Swift_属性
  18. TCP系列24—重传—14、F-RTO虚假重传探测
  19. Annotation:系统内建Annotation
  20. Cocos2d-x 网络编程

热门文章

  1. cocos2d-x 之 CCArray 源码分析(2)
  2. 【Map】获取字符串中,每一个字母出现的次数
  3. #import、#include、@class、@protocol、@interface
  4. Spring MVC 上传文件
  5. VO,DO,DTO,PO,POJO,EJB
  6. JS JQuery初始化
  7. Count Colour_poj2777(线段树+位)
  8. 【09_242】Valid Anagram
  9. Zabbix3.0 自动电话报障
  10. 精确运算--BigDecimal