spring和ehcache整合,实现基于注解的缓存实现
2024-10-18 16:09:19
要实现基于注解的缓存实现,要求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注解删除缓存
最新文章
- centos 20T硬盘(超过16T)分区
- Linq专题之集合初始化器
- Oracle数据库语句大全
- 寻找代表元(codevs 2776)
- node基础 --全局
- GUID
- LCD驱动 15 -2
- log4net自定义字段写入SqlServer数据库 ASP.net
- IE 6/7下自赋值导致 overflow 溢出
- CSAPP:cachelab(1)
- Latch-up 閂鎖效應 &; 靜電放電模式
- P1316 丢瓶盖--(二分答案)
- ubuntu16.10安装网易云音乐
- matlib实现梯度下降法
- html的a标签的 href 和 onclick。
- Bootstrap组件系列之福利篇几款好用的组件(推荐)
- Swift_属性
- TCP系列24—重传—14、F-RTO虚假重传探测
- Annotation:系统内建Annotation
- Cocos2d-x 网络编程
热门文章
- cocos2d-x 之 CCArray 源码分析(2)
- 【Map】获取字符串中,每一个字母出现的次数
- #import、#include、@class、@protocol、@interface
- Spring MVC 上传文件
- VO,DO,DTO,PO,POJO,EJB
- JS JQuery初始化
- Count Colour_poj2777(线段树+位)
- 【09_242】Valid Anagram
- Zabbix3.0 自动电话报障
- 精确运算--BigDecimal