缓存插件 Spring支持EHCache缓存
Spring仅仅是提供了对缓存的支持,但它并没有任何的缓存功能的实现,spring使用的是第三方的缓存框架来实现缓存的功能。其中,spring对EHCache提供了很好的支持。
在介绍Spring的缓存配置之前,我们先看一下EHCache是如何配置。
<?xml version="1.0" encoding="UTF-8" ?>
<ehcache>
<!-- 定义默认的缓存区,如果在未指定缓存区时,默认使用该缓存区 -->
<defaultCache maxElementsInMemory="500" eternal="true"
overflowToDisk="false" memoryStoreEvictionPolicy="LFU">
</defaultCache>
<!-- 定义名字为"dao.select"的缓存区 -->
<cache name="dao.select" maxElementsInMemory="500" eternal="true"
overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />
</ehcache>
由于Spring的缓存机制是基于Spring的AOP,那么在Spring Cache中应该存在着一个Advice。没错,在Spring Cache中的Advice是存在的,它就是org.springframework.cache.Cache。我们看一下它的接口定义:
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.cache; /**
* Interface that defines the common cache operations.
*
* <b>Note:</b> Due to the generic use of caching, it is recommended that
* implementations allow storage of <tt>null</tt> values (for example to
* cache methods that return {@code null}).
*
* @since 3.1
*/
public interface Cache { /**
* Return the cache name.
*/
String getName(); /**
* Return the the underlying native cache provider.
*/
Object getNativeCache(); /**
* Return the value to which this cache maps the specified key. Returns
* <code>null</code> if the cache contains no mapping for this key.
* @param key key whose associated value is to be returned.
* @return the value to which this cache maps the specified key,
* or <code>null</code> if the cache contains no mapping for this key
*/
ValueWrapper get(Object key); /**
* Associate the specified value with the specified key in this cache.
* <p>If the cache previously contained a mapping for this key, the old
* value is replaced by the specified value.
* @param key the key with which the specified value is to be associated
* @param value the value to be associated with the specified key
*/
void put(Object key, Object value); /**
* Evict the mapping for this key from this cache if it is present.
* @param key the key whose mapping is to be removed from the cache
*/
void evict(Object key); /**
* Remove all mappings from the cache.
*/
void clear(); /**
* A (wrapper) object representing a cache value.
*/
interface ValueWrapper { /**
* Return the actual value in the cache.
*/
Object get();
} }
evict,put方法就是Advice的功能方法,或者可以这样去理解。
但spring并不是直接使用org.springframework.cache.Cache,spring把Cache对象交给org.springframework.cache.CacheManager来管理,下面是org.springframework.cache.CacheManager接口的定义:
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.cache; import java.util.Collection; /**
* A manager for a set of {@link Cache}s.
*
* @since 3.1
*/
public interface CacheManager { /**
* Return the cache associated with the given name.
* @param name cache identifier (must not be {@code null})
* @return associated cache, or {@code null} if none is found
*/
Cache getCache(String name); /**
* Return a collection of the caches known by this cache manager.
* @return names of caches known by the cache manager.
*/
Collection<String> getCacheNames(); }
在spring对EHCache的支持中,org.springframework.cache.ehcache.EhCacheManager就是org.springframework.cache.CacheManager的一个实现
<!--
该Bean是一个org.springframework.cache.CacheManager对象
属性cacheManager是一个net.sf.ehcache.CacheManager对象
-->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager">
<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache-config.xml"></property>
</bean>
</property>
</bean>
基于xml方式的缓存配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
"> <context:component-scan base-package="com.sin90lzc"></context:component-scan>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager">
<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache-config.xml"></property>
</bean>
</property>
</bean> <cache:advice id="cacheAdvice" cache-manager="cacheManager">
<cache:caching>
<cache:cacheable cache="dao.select" method="select"
key="#id" />
<cache:cache-evict cache="dao.select" method="save"
key="#obj" />
</cache:caching>
</cache:advice> <aop:config>
<aop:advisor advice-ref="cacheAdvice" pointcut="execution(* com.sin90lzc.train.spring_cache.simulation.DaoImpl.*(..))"/>
</aop:config>
</beans>
注解驱动缓存配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"> <context:component-scan base-package="com.sin90lzc"></context:component-scan> <!--
该Bean是一个org.springframework.cache.CacheManager对象
属性cacheManager是一个net.sf.ehcache.CacheManager对象
-->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager">
<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache-config.xml"></property>
</bean>
</property>
</bean> <cache:annotation-driven />
<!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
<!-- <cache:annotation-driven cache-manager="cacheManager"/> --> </beans>
package com.sin90lzc.train.spring_cache.simulation; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component; @Component
public class DaoImpl implements Dao { /**
* value定义了缓存区(缓存区的名字),每个缓存区可以看作是一个Map对象
* key作为该方法结果缓存的唯一标识,
*/
@Cacheable(value = { "dao.select" },key="#id")
@Override
public Object select(int id) {
System.out.println("do in function select()");
return new Object();
} @CacheEvict(value = { "dao.select" }, key="#obj")
@Override
public void save(Object obj) {
System.out.println("do in function save(obj)");
} }
@Cacheable:负责将方法的返回值加入到缓存中
@CacheEvict:负责清除缓存
@Cacheable 支持如下几个参数:
value:缓存位置名称,不能为空,如果使用EHCache,就是ehcache.xml中声明的cache的name
key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL
condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL
例如:
//将缓存保存进andCache,并使用参数中的userId加上一个字符串(这里使用方法名称)作为缓存的key
@Cacheable(value="andCache",key="#userId + 'findById'")
public SystemUser findById(String userId) {
SystemUser user = (SystemUser) dao.findById(SystemUser.class, userId);
return user ;
}
//将缓存保存进andCache,并当参数userId的长度小于32时才保存进缓存,默认使用参数值及类型作为缓存的key
@Cacheable(value="andCache",condition="#userId.length < 32")
public boolean isReserved(String userId) {
System.out.println("hello andCache"+userId);
return false;
}
@CacheEvict 支持如下几个参数:
value:缓存位置名称,不能为空,同上
key:缓存的key,默认为空,同上
condition:触发条件,只有满足条件的情况才会清除缓存,默认为空,支持SpEL
allEntries:true表示清除value中的全部缓存,默认为false
例如:
//清除掉指定key的缓存
@CacheEvict(value="andCache",key="#user.userId + 'findById'")
public void modifyUserRole(SystemUser user) {
System.out.println("hello andCache delete"+user.getUserId());
}
//清除掉全部缓存
@CacheEvict(value="andCache",allEntries=true)
public final void setReservedUsers(String[] reservedUsers) {
System.out.println("hello andCache deleteall");
}
缓存插件 Spring支持EHCache缓存的更多相关文章
- Spring自定义缓存管理及配置Ehcache缓存
spring自带缓存.自建缓存管理器等都可解决项目部分性能问题.结合Ehcache后性能更优,使用也比较简单. 在进行Ehcache学习之前,最好对Spring自带的缓存管理有一个总体的认识. 这篇文 ...
- Spring MVC3 + Ehcache 缓存实现
转自:http://www.coin163.com/it/490594393324999265/spring-ehcache Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了 ...
- 玩转spring ehcache 缓存框架
一.简介 Ehcache是一个用Java实现的使用简单,高速,实现线程安全的缓存管理类库,ehcache提供了用内存,磁盘文件存储,以及分布式存储方式等多种灵活的cache管理方案.同时ehcache ...
- spring ehcache 缓存框架
一.简介 Ehcache是一个用Java实现的使用简单,高速,实现线程安全的缓存管理类库,ehcache提供了用内存,磁盘文件存储,以及分布式存储方式等多种灵活的cache管理方案.同时ehcache ...
- 以Spring整合EhCache为例从根本上了解Spring缓存这件事(转)
前两节"Spring缓存抽象"和"基于注解驱动的缓存"是为了更加清晰的了解Spring缓存机制,整合任何一个缓存实现或者叫缓存供应商都应该了解并清楚前两节,如果 ...
- Spring Boot 集成 Ehcache 缓存,三步搞定!
作者:谭朝红 www.ramostear.com/articles/spring_boot_ehcache.html 本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序 ...
- spring使用ehcache实现页面缓存
ehcache缓存最后一篇,介绍页面缓存: 如果将应用的结构分为"page-filter-action-service-dao-db",那page层就是最接近用户的一层,一些特定的 ...
- spring中使用缓存
一.启用对缓存的支持 Spring 对缓存的支持最简单的方式就是在方法上添加@Cacheable和@CacheEvict注解, 再添加注解之前,必须先启用spring对注解驱动的支持,基于java的配 ...
- 简单聊聊Ehcache缓存
最近工作没有那么忙,有时间来写写东西.今年的系统分析师报名已经开始了,面对历年的真题,真的难以入笔,所以突然对未来充满了担忧,还是得抓紧时间学习技术. 同事推了一篇软文,看到了这个Ehcache,感觉 ...
随机推荐
- 【实践】获取CKEditor的html文本、纯文本、被选中的内容及赋值
<%=Html.TextAreaFor(Model => Model.WORK_INTRODUCTION)%> <script type="text/javasc ...
- CSU 1081 集训队分组
题意:有n个学生,比了一场比赛,但是榜单看不到了.现在告诉你m段信息,每段信息的内容是(a,b),表示a的排名比b的高.问你能不能根据这些信息得出这场比赛的前k名. 思路:用拓扑排序找出一组符合k个人 ...
- 从Maya中导入LightMap到unity中
导入步骤 1.在Maya中为每一个模型烘焙好帖图(tif格式),会发现烘焙好的图和UV是一一对应的 2.把模型和烘焙帖图导入到Unity中 3.选中材质,修改Shader为 Legacy Shader ...
- Cookie测试工具小汇
现在很多网站都用到Cookies,特别是用户的登陆以及购物网站的购物车. Cookies 通常用来存储用户信息和用户在某应用系统的操作,当一个用户使用Cookies 访问了某一个应用系统时,Web 服 ...
- 对于a标签点击之后可以发邮件和打电话的功能实现
<ul> <li><i class="phone"></i><a href="tel:021-69976089&qu ...
- python算法:rangeBitwiseAnd(连续整数的与)
def rangeBitwiseAnd(self, m, n): i = 0 while m != n: m >>= 1 n >>= 1 i += 1 return n < ...
- 21SpringMvc_异步发送表单数据到Bean,并响应JSON文本返回(这篇可能是最重要的一篇了)
这篇文章实现三个功能:1.在jsp页面点击一个按钮,然后跳转到Action,在Action中把Emp(int id ,String salary,Data data)这个实体变成JSON格式返回到页面 ...
- 15Spring_AOP编程(AspectJ)_抛出通知
- RDLC系列之三 图片显示
一.头像效果
- 最近火到不行的微信小程序的常识
满网都是微信小程序,技术dog们不关注都不行了.先别忙着去学怎么开发小程序,先纠正一下你对微信小程序的三观吧~~~~ 小程序目前被炒得沸沸扬扬,无数媒体和企业借机获取阅读流量. 这再次证明一点,微信想 ...