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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/cachehttp://www.springframework.org/schema/cache/spring-cache-3.1.xsdhttp://www.springframework.org/schema/aophttp://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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/cachehttp://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")@Overridepublic Object select(int id) {System.out.println("do in function select()");return new Object();}@CacheEvict(value = { "dao.select" }, key="#obj")@Overridepublic 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());
}
&nbsp;//清除掉全部缓存
@CacheEvict(value="andCache",allEntries=true)
public final void setReservedUsers(String[] reservedUsers) {System.out.println("hello andCache deleteall");
}

转载于:https://www.cnblogs.com/hwaggLee/p/4443155.html

缓存插件 Spring支持EHCache缓存相关推荐

  1. Spring测试上下文缓存+ AspectJ @Transactional + Ehcache的痛苦

    您在使用AspectJ @Transactionals和Spring吗? 您是否有多个SessionFactory,也许一个用于嵌入式数据库进行单元测试,一个用于实际数据库进行集成测试? 您是否遇到这 ...

  2. SpringBoot集成Cache缓存(Ehcache缓存框架,注解方式)

    1.说明 Spring定义了CacheManager和Cache接口, 用来统一不同的缓存技术, 例如JCache,EhCache,Hazelcast,Guava,Redis等. 本文通过Spring ...

  3. MyBatis-24MyBatis缓存配置【集成EhCache】

    文章目录 概述 EhCache概述 特点 EhCache架构图 示例 1.添加mybatis-ehcache依赖 2. 配置EhCache 3.修改PrivilegeMapper.xml中的缓存配置 ...

  4. 【转】最佳 WordPress 缓存插件:WP Super Cache

    WP Super Cache 是 WordPress 官方开发人员 Donncha 开发,是当前最高效也是最灵活的 WordPress 静态缓存插件.它把整个网页直接生成 HTML 文件,这样 Apa ...

  5. WP Super Cache和W3 Total Cache缓存插件性能总结

    WP Super Cache和W3 Total Cache缓存插件都致力于让你的wordpress速度更快,响应更及时.哪一款缓存插件更适合优化我们的WP站点呢?我用了两款插件,谈下体会: 缓存插件很 ...

  6. Chrome(谷歌)浏览器一键清缓存插件使用教程

    Chrome(谷歌)浏览器一键清缓存插件使用教程 一键清缓存插件教程 一键清缓存插件教程 1.首先下载谷歌一键清缓存插件,下载后的文件应该是".crs"格式的文件. 2.然后将.c ...

  7. Hibernate缓存原理与策略 Hibernate缓存原理:

    Hibernate缓存原理: 对于Hibernate这类ORM而言,缓存显的尤为重要,它是持久层性能提升的关键.简单来讲Hibernate就是对JDBC进行封装,以实现内部状态的管理,OR关系的映射等 ...

  8. MyBatis→优缺点、select延迟加载、接口式MyBatis编程、一级缓存、二级缓存、集成Redis自定义缓存、Log4j

    MyBatis优缺点 select延迟加载 接口式MyBatis编程 一级缓存 一级缓存原理 一级缓存命中原则 一级缓存销毁 一级缓存避免脏读不可重复读 一级缓存与spring@事务 二级缓存 与一级 ...

  9. (转)使用 Spring缓存抽象 支持 EhCache 和 Redis 混合部署

    背景:最近项目组在开发本地缓存,其中用到了redis和ehcache,但是在使用注解过程中发现两者会出现冲突,这里给出解决两者冲突的具体方案. spring-ehcache.xml配置: <?x ...

最新文章

  1. 你动、蒙娜丽莎跟着一起动,OpenCV这么用,表情口型造假更难防了
  2. 在哪里能收到python实例代码-Python分类测试代码实例汇总
  3. 思科推出EnergyWise合作伙伴计划
  4. python commands模块在python3.x被subprocess取代
  5. 模板原理和操作数据类的观点【艰难的一天,慢慢的会过去的】
  6. Final Michael Scofield
  7. TestNG如何disable一些case
  8. 浅谈密码学中数论基础
  9. 在Mac OS X下编译 boost|building boost library under mac os x
  10. css3 border
  11. 构建大型网站架构服务器集群(转)
  12. javascript变量说明
  13. 软件multisim的安装教程
  14. 悬赏任务源码系统带app小程序源码基于php开源版
  15. html 二维表_Qrcode 二维码 API 接入方法,任何内容都可以生成二维码
  16. 苹果 UDID设备满100台的处理方法
  17. ios 换电脑继续使用csr 证书等。
  18. 【FAQ】应用集成HMS Core部分服务出现“ 6003报错”情况的解决方法来啦
  19. 反汇编和二进制分析工具清单
  20. PowerBI - 10.功能丰富的报表展示工具

热门文章

  1. html多选框 jquery,jQuery Select多选
  2. plc的时代背景_PLC发明史
  3. oxford5k和paris6k数据集介绍_sklearn函数:KFold(分割训练集和测试集)
  4. pythonscrapy爬虫_零基础写python爬虫之使用Scrapy框架编写爬虫
  5. currentdate mysql_Mysql】Mysql中CURRENT_TIMESTAMP,CURRENT_DATE,CURRENT_TIME,now(),sysdate()各项值的区别...
  6. 云计算具有什么平台_漫话:什么是云计算?
  7. rsync + inotify
  8. k8s提交镜像到harbor仓库
  9. 防火墙(3)——iptables(1)
  10. 颜色分类—leetcode75