简介:

  Spring 3.1中开始对缓存提供支持,核心思路是对方法的缓存,当开发者调用一个方法时,将方法的参数和返回值作为key/value缓存起来,当再次调用该方法时,如果缓存中有数据,就直接从缓存中获取,否则再去执行该方法。但是,Spring 中并未提供缓存的实现,而是提供了-套缓存API,开发者可以自由选择缓存的实现。

  目前Spring Boot支持的缓存有如下几种::  

  JCache (JSR-107)
  EhCache 2.x
  Hazelcast
  Infinispan
  Couchbase
  Redis
  Caffeine
  Simple

使用:

pom.xml

 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Encache配置文件:ehcache.xml

  这是一个常规的Ehcache 配置文件,提供了两个缓存策略,一个是默认的,另一个名为book _cache。

   其中,name表示缓存名称:

   maxElementsInMemory 表示缓存最大个数:

   etemal 表示缓存对象是否永久有效,一旦设置了永久有效,timcout 将不起作用:

   timeToldleSeconds 表示缓存对象在失效前的允许闲置时间(单位:秒),当etermal对象不是永久有效时,该属性才生效:

   timeToLiveSeconds表示缓存对象在失效前允许存活的时间(单位:秒),当eternal-false对象不是永久有效时,该属性才生效:

   overflowToDisk 表示当内存中的对象数量达到maxElementsInMemory时,Eheache 是否将对象写到磁盘中:

   diskxpiryTheadntervalseconds 表示磁盘失效线程运行时间间隔。

<ehcache>
<diskStore path="java.io.tmpdir/cache"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache name="book_cache"
maxElementsInMemory="10000"
eternal="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="10"/>
</ehcache>

开启缓存:@EnableCaching注解

@SpringBootApplication
@EnableCaching
public class CacheApplication {
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}
}

创建实体类和service

public class Book implements Serializable {
private Integer id;
private String name;
private String author; 。。。。。
}
@Service
@CacheConfig(cacheNames = "book_cache")
public class BookDao {
@Autowired
MyKeyGenerator myKeyGenerator;
@Cacheable(keyGenerator = "myKeyGenerator")
public Book getBookById(Integer id) {
System.out.println("getBookById");
Book book = new Book();
book.setId(id);
book.setName("三国演义");
book.setAuthor("罗贯中");
return book;
}
@CachePut(key = "#book.id")
public Book updateBookById(Book book) {
System.out.println("updateBookById");
book.setName("三国演义2");
return book;
}
@CacheEvict(key = "#id")
public void deleteBookById(Integer id) {
System.out.println("deleteBookById");
}
}

  在Service层上添加@CacheConfig注解指明使用的缓存的名字,这个配置可选,若不使用@CacheConfig注解,则直接在@Cacheable注解中指明缓存名字。

  在getBookById方法上添加@Cacheable注解表示对该方法进行缓存,默认情况下,缓存的key是方法的参数,缓存的value是方法的返回值。当开发者在其他类中调用该方法时,首先会根据调用参数查看缓存中是否有相关数据,若有,则直接使用缓存数据,该方法不会执行,否则执行该方法,执行成功后将返回值缓存起来,但若是在当前类中调用该方法,则缓存不会生效

  @Cacheable注解中还有一个属性condition用来描述缓存的执行时机,例如@Cacheable(condition= "#id%2= =0")表示当id对2取模为0时才进行缓存,否则不缓存。

  如果开发者不想使用默认的key,也可以自定义key,key = "#book.id"表示缓存的key为参数book对象中id 的值,key = "#id"表示缓存的key为参数id.

  除了这种使用参数定义key的方式之外,Spring 还提供了一个root对象用来生成key,如表。

  @CachePut注解一般用于数据更新方法上,与@Cacheable 注解不同,添加了@CachePut注解的方法每次在执行时都不去检查缓存中是否有数据,而是直接执行方法,然后将方法的执行结果缓存起来,如果该key对应的数据已经被缓存起来了,就会覆盖之前的数据,这样可以避免再次加载数据时获取到脏数据。同时,@CachePut具有和@Cacheable类似的属性,这里不再赘述。

  @CacheEvict注解一般用于删除方法上,表示移除一个key对应的缓存。@CacheEvict注解有两个特殊的属性: allEntries和beforeInvocation, 其中allEntries表示是否将所有的缓存数据都移除,默认为false, beforeInvocation表示是否在方法执行之前移除缓存中的数据,默认为false,即在方法执行之后移除缓存中的数据。

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class CacheApplicationTests {
@Autowired
BookDao bookDao;
@Test
public void contextLoads() {
bookDao.getBookById(1);
bookDao.getBookById(1); bookDao.deleteBookById(1); Book b3 = bookDao.getBookById(1);
System.out.println("b3:"+b3); Book b = new Book();
b.setName("三国演义");
b.setAuthor("罗贯中");
b.setId(1);
bookDao.updateBookById(b); Book b4 = bookDao.getBookById(1);
System.out.println("b4:"+b4);
}
}

控制台:


getBookById
deleteBookById
getBookById
b3:Book{id=1, name='三国演义', author='罗贯中'} 
updateBookById b4:Book{id=1, name='三国演义', author='罗贯中'}

SpringBoot缓存 --(一)EhCache2.X的更多相关文章

  1. SpringBoot缓存之redis--最简单的使用方式

    第一步:配置redis 这里使用的是yml类型的配置文件 mybatis: mapper-locations: classpath:mapping/*.xml spring: datasource: ...

  2. spring boot学习(十三)SpringBoot缓存(EhCache 2.x 篇)

    SpringBoot 缓存(EhCache 2.x 篇) SpringBoot 缓存 在 Spring Boot中,通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManag ...

  3. SpringBoot缓存管理(二) 整合Redis缓存实现

    SpringBoot支持的缓存组件 在SpringBoot中,数据的缓存管理存储依赖于Spring框架中cache相关的org.springframework.cache.Cache和org.spri ...

  4. springboot缓存开发

    前言:缓存在开发中是一个必不可少的优化点,近期在公司的项目重构中,关于缓存优化了很多点,比如在加载一些数据比较多的场景中,会大量使用缓存机制提高接口响应速度,简介提升用户体验.关于缓存,很多人对它都是 ...

  5. springboot缓存的使用

    spring针对各种缓存实现,抽象出了CacheManager接口,用户使用该接口处理缓存,而无需关心底层实现.并且也可以方便的更改缓存的具体实现,而不用修改业务代码.下面对于在springboot中 ...

  6. springboot缓存及连接池配置

    参见https://coding.imooc.com/lesson/117.html#mid=6412 1.springboot的springweb自己默认以及配置好了缓存,只需要在主文件(XxxAp ...

  7. SpringBoot 缓存注解 与EhCache的使用

    在SpringBoot工程中配置EhCache缓存 1.在src/main/resources下新建ehcache.xml文件 eternal=true //缓存永久有效,false相反 maxEle ...

  8. SpringBoot 缓存模块

    默认的缓存配置 在诸多的缓存自动配置类中, SpringBoot默认装配的是SimpleCacheConfigguration, 他使用的CacheManager是 CurrentMapCacheMa ...

  9. 转载-springboot缓存开发

    转载:https://www.cnblogs.com/wyq178/p/9840985.html   前言:缓存在开发中是一个必不可少的优化点,近期在公司的项目重构中,关于缓存优化了很多点,比如在加载 ...

随机推荐

  1. Ninja构建系统入门

    1. 介绍 开篇先介绍.先甩资料给大家看,之后再自己演示一下基本使用.Ninja 是Google的一名程序员推出的注重速度的构建工具,一般在Unix/Linux上的程序通过make/makefile来 ...

  2. initramfs打包集成rootfs到image镜像及linux rootfs的正常启动

    最近的项目中需要在仿真机haps及VDK上集成rootfs,中间遇到一些问题,在此整理记录以备忘. rootfs里面集成的busybox版本1.29.3 (buildroot环境中自带) kernel ...

  3. 工具之awk

    转自:http://www.cnblogs.com/ggjucheng/archive/2013/01/13/2858470.html awk是一个强大的文本分析工具,相对于grep的查找,sed的编 ...

  4. Redhat6.7 切换Centos yum源

    转自:http://inlhx.iteye.com/blog/2336729 RedHat 更换Yum源 1.检查yum包 rpm -qa |grep yum 2.删除自带包 rpm -aq | gr ...

  5. A novel multi-swarm particle swarm optimization with dynamic learning strategy(一种新颖的具有动态学习策略的多种群粒子群优化算法)

    1.核心 在每个子种群的粒子被划分为普通粒子(ordinary particles)和交流粒子(communication particles),在每次迭代过程中,不同的粒子执行不同的进化操作.普通粒 ...

  6. java操作数组转list集合删除元素报错ConcurrentModificationException

    public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>( ...

  7. linux启动Firefox报错,及解决方法

    今天在安装Firefox时,出现如下错误 [root@localhost ~]# firefox XPCOMGlueLoad error for file /usr/lib64/firefox/lib ...

  8. 使用信号管理nginx的父子进程

    master进程 通过CHLD监控worker进程,worker异常退出,通过CHLD信号拉起worker进程. 接收信号 TERM,INT信号表示立刻停止worker进程 QUIT信号表示优雅的停止 ...

  9. 让Android模拟器速度飞起来_Eclipse+BlueStacks调试Android应用【2012-10-30】

    谨将此文献给无真机进行调试的各位同仁们,有真机的幸运儿请自觉飘过 原文地址:http://www.cnblogs.com/hbbbs/archive/2012/10/30/2746950.html 长 ...

  10. DOCKER 学习笔记8 Docker Swarm 集群搭建

    前言 在前面的文章中,已经介绍如何在本地通过Docker Machine 创建虚拟Docker 主机,以及也可以在本地Windows 创建虚拟主机,也是可以使用的.这一节,我们将继续学习 Docker ...