EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。

  ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心容量问题。

  spring-boot是一个快速的集成框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

  由于spring-boot无需任何样板化的配置文件,所以spring-boot集成一些其他框架时会有略微的不同。

  1.spring-boot是一个通过maven管理的jar包的框架,集成ehcache需要的依赖如下

 <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.8.3</version>
</dependency>
2.使用ehcache,我们需要一个ehcache.xml来定义一些cache的属性。
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir/Tmp_EhCache" />
<defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" /> <cache name="demo" eternal="false" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" /> </ehcache>

解释下这个xml文件中的标签。

  (1).diskStore: 为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:    
             user.home – 用户主目录
             user.dir  – 用户当前工作目录
             java.io.tmpdir – 默认临时文件路径

  (2).defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。

(3).cache:自定缓存策略,为自定义的缓存策略。参数解释如下:

    cache元素的属性:   
            name:缓存名称                  
            maxElementsInMemory:内存中最大缓存对象数                  
            maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大                  
            eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false                
            overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。                  
            diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。               
            diskPersistent:是否缓存虚拟机重启期数据                  
            diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒     
            timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态                  
            timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义     
            memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。

  3.将ehcache的管理器暴露给spring的上下文容器,

@Configuration
// 标注启动了缓存
@EnableCaching
public class CacheConfiguration { /*
* ehcache 主要的管理器
*/
@Bean(name = "appEhCacheCacheManager")
public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
return new EhCacheCacheManager (bean.getObject ());
} /*
* 据shared与否的设置,Spring分别通过CacheManager.create()或new CacheManager()方式来创建一个ehcache基地.
*/
@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean ();
cacheManagerFactoryBean.setConfigLocation (new ClassPathResource ("conf/ehcache-app.xml"));
cacheManagerFactoryBean.setShared (true);
return cacheManagerFactoryBean;
}
}

 @Configuration:为spring-boot注解,主要标注此为配置类,优先扫描。

    @Bean:向spring容器中加入bean。

  至此所有的配置都做好了,通过spring-boot进行集成框架就是这么简单。

  4.使用ehcache

    使用ehcache主要通过spring的缓存机制,上面我们将spring的缓存机制使用了ehcache进行实现,所以使用方面就完全使用spring缓存机制就行了。
    具体牵扯到几个注解:

    @Cacheable:负责将方法的返回值加入到缓存中,参数3
    @CacheEvict:负责清除缓存,参数4

     参数解释:

    value:缓存位置名称,不能为空,如果使用EHCache,就是ehcache.xml中声明的cache的name
    key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL
    condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL

    allEntries:CacheEvict参数,true表示清除value中的全部缓存,默认为false

  不多说,直接上代码:

@Service
public class CacheDemoServiceImpl implements CacheDemoService { /**
* 缓存的key
*/
public static final String THING_ALL_KEY = "\"thing_all\"";
/**
* value属性表示使用哪个缓存策略,缓存策略在ehcache.xml
*/
public static final String DEMO_CACHE_NAME = "demo"; @CacheEvict(value = DEMO_CACHE_NAME,key = THING_ALL_KEY)
@Override
public void create(Thing thing){
Long id = getNextId ();
thing.setId (id);
data.put (id, thing);
} @Cacheable(value = DEMO_CACHE_NAME,key = "#thing.getId()+'thing'")
@Override
public Thing findById(Long id){
System.err.println ("没有走缓存!" + id);
return data.get (id);
} @Cacheable(value = DEMO_CACHE_NAME,key = THING_ALL_KEY)
@Override
public List<Thing> findAll(){
return Lists.newArrayList (data.values ());
} @Override
@CachePut(value = DEMO_CACHE_NAME,key = "#thing.getId()+'thing'")
@CacheEvict(value = DEMO_CACHE_NAME,key = THING_ALL_KEY)
public Thing update(Thing thing){
System.out.println (thing);
data.put (thing.getId (), thing);
return thing;
} @CacheEvict(value = DEMO_CACHE_NAME)
@Override
public void delete(Long id){
data.remove (id);
} }
5.只需要通过注解在service层方法上打注解便可以使用缓存,在find**上存入缓存,在delete**,update**上清除缓存。
具体pom.xml文件如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.lclc.boot</groupId>
<artifactId>boot-cache</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>17.0</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.8.3</version>
</dependency>
</dependencies> <dependencyManagement>
<dependencies>
</dependencies>
</dependencyManagement> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> <repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories> </project>

springBoot整合ecache缓存的更多相关文章

  1. SpringBoot 整合 Redis缓存

    在我们的日常项目开发过程中缓存是无处不在的,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用现在非常流行的NoSQL数据库(Redis)来实现我们的缓存需求. Spr ...

  2. springboot整合redis缓存

    使用springBoot添加redis缓存需要在POM文件里引入 org.springframework.bootspring-boot-starter-cacheorg.springframewor ...

  3. springboot整合redis缓存一些知识点

    前言 最近在做智能家居平台,考虑到家居的控制需要快速的响应于是打算使用redis缓存.一方面减少数据库压力另一方面又能提高响应速度.项目中使用的技术栈基本上都是大家熟悉的springboot全家桶,在 ...

  4. SpringBoot整合guava缓存

    1.pom文件 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  5. SpringBoot整合redis缓存(一)

    准备工作 1.Linux系统 2.安装redis(也可以安装docker,然后再docker中装redis,本文章就直接用Linux安装redis做演示) redis下载地址: 修改redis,开启远 ...

  6. springboot 整合ehcache缓存

    1.CacheManager Spring Boot默认集成CacheManager,如下包所示: 可以看出springboot自动配置了 JcacheCacheConfiguration. EhCa ...

  7. 转载-Springboot整合ehcache缓存

    转载:https://www.cnblogs.com/xzmiyx/p/9897623.html EhCache是一个比较成熟的Java缓存框架,最早从hibernate发展而来, 是进程中的缓存系统 ...

  8. Springboot整合Ehcache缓存

    Pom.xml导包 <!-- ehcache --> <dependency> <groupId>org.springframework.boot</grou ...

  9. springboot 整合GuavaCache缓存

    Guava Cache是一种本地缓存机制,之所以叫本地缓存,是因为它不会把缓存数据放到外部文件或者其他服务器上,而是存放到了应用内存中. Guava Cache的优点是:简单.强大.轻量级. Guav ...

随机推荐

  1. 【深入理解JAVA虚拟机】第二部分.内存自动管理机制.1.内存区域

    1.内存区域 根据<Java虚拟机规范(Java SE 7版)> 的规定,Java虚拟机所管理的内存将会包括以下几个运行时数据区域,如图所示.  程序计数器 当前线程所执行的字节码的行号指 ...

  2. 条件独立(conditional independence) 结合贝叶斯网络(Bayesian network) 概率有向图 (PRML8.2总结)

    转:http://www.cnblogs.com/Dzhouqi/p/3204481.html本文会利用到上篇,博客的分解定理,需要的可以查找上篇博客 D-separation对任何用有向图表示的概率 ...

  3. 数据库JDBC的基本内容

    JDBC 基本流程 首先向项目中导入jar包 创建如下代码 Class.forName("com.mysql.jdbc.Driver"); String url = "j ...

  4. C++、Java、Objective-C、Swift 二进制兼容测试

    鉴于目前动态库在iOS App中使用越来越广泛,二进制的兼容问题可能会成为一个令人头疼的问题.本文主要对比一下C++.Java.Objecive-C和Swift的二进制兼容问题. iOS端动态库使用情 ...

  5. Unity3D十款最火的的插件推荐

    作为当前最主流的3D游戏引擎之中的一个.Unity拥有大量第三方插件和工具帮助开发人员提升工作效率. 我们摘选了十款最受欢迎的工具推荐给大家.类别包括2D开发.UI设计.原型制作.着色.特效等,涉及了 ...

  6. 牛客网多校训练第三场 C - Shuffle Cards(Splay / rope)

    链接: https://www.nowcoder.com/acm/contest/141/C 题意: 给出一个n个元素的序列(1,2,...,n)和m个操作(1≤n,m≤1e5),每个操作给出两个数p ...

  7. Hibernate之CRUD实践

    Hibernate作为一个高度封装的持久层框架,曾经是非常牛逼的,现在虽然应用不是特别广,比如我前公司主要是做OA的,应用的框架就是Spring+SpringMVC+Hibernate. Hibern ...

  8. 关于js点击事件出现 xx is not defined at HTMLAnchorElement.onclick 的问题

    测试: html: <button onclick="abc();">点我点我!</button> js: function abc(){ alert(“1 ...

  9. 撸一个简单的MVVM例子

    我个人以为mvvm框架里面最重要的一点就是VM这部分,它要与Model层建立联系,将Model层转换成可以被View层识别的数据结构:其次也要同View建立联系,将数据及时更新到View层上,并且响应 ...

  10. 【微信开发】微信开发模式 api 接口文档简介

    微信公众平台分为订阅号和服务号,服务号提供9大接口,需要通过微信认证后才能使用这些接口.认证费用300元.下面是接口的大致介绍: 1. 语音识别:通过语音识别接口,用户发送的语音,将会同时给出语音识别 ...