spring和ehcache整合,实现基于注解的缓存实现

时间:2023-03-09 16:32:47
spring和ehcache整合,实现基于注解的缓存实现

要实现基于注解的缓存实现,要求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注解删除缓存