简介:

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

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

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

使用:

pom.xml

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-cache</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-web</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>net.sf.ehcache</groupId>
  11. <artifactId>ehcache</artifactId>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-data-redis</artifactId>
  16. </dependency>

Encache配置文件:ehcache.xml

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

   其中,name表示缓存名称:

   maxElementsInMemory 表示缓存最大个数:

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

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

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

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

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

  1. <ehcache>
  2. <diskStore path="java.io.tmpdir/cache"/>
  3. <defaultCache
  4. maxElementsInMemory="10000"
  5. eternal="false"
  6. timeToIdleSeconds="120"
  7. timeToLiveSeconds="120"
  8. overflowToDisk="false"
  9. diskPersistent="false"
  10. diskExpiryThreadIntervalSeconds="120"
  11. />
  12. <cache name="book_cache"
  13. maxElementsInMemory="10000"
  14. eternal="true"
  15. timeToIdleSeconds="120"
  16. timeToLiveSeconds="120"
  17. overflowToDisk="true"
  18. diskPersistent="true"
  19. diskExpiryThreadIntervalSeconds="10"/>
  20. </ehcache>

开启缓存:@EnableCaching注解

  1. @SpringBootApplication
  2. @EnableCaching
  3. public class CacheApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(CacheApplication.class, args);
  6. }
  7. }

创建实体类和service

  1. public class Book implements Serializable {
  2. private Integer id;
  3. private String name;
  4. private String author;
  5.  
  6. 。。。。。
  7. }
  1. @Service
  2. @CacheConfig(cacheNames = "book_cache")
  3. public class BookDao {
  4. @Autowired
  5. MyKeyGenerator myKeyGenerator;
  6. @Cacheable(keyGenerator = "myKeyGenerator")
  7. public Book getBookById(Integer id) {
  8. System.out.println("getBookById");
  9. Book book = new Book();
  10. book.setId(id);
  11. book.setName("三国演义");
  12. book.setAuthor("罗贯中");
  13. return book;
  14. }
  15. @CachePut(key = "#book.id")
  16. public Book updateBookById(Book book) {
  17. System.out.println("updateBookById");
  18. book.setName("三国演义2");
  19. return book;
  20. }
  21. @CacheEvict(key = "#id")
  22. public void deleteBookById(Integer id) {
  23. System.out.println("deleteBookById");
  24. }
  25. }

  在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,即在方法执行之后移除缓存中的数据。

测试:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class CacheApplicationTests {
  4. @Autowired
  5. BookDao bookDao;
  6. @Test
  7. public void contextLoads() {
  8. bookDao.getBookById(1);
  9. bookDao.getBookById(1);
  10.  
  11. bookDao.deleteBookById(1);
  12.  
  13. Book b3 = bookDao.getBookById(1);
  14. System.out.println("b3:"+b3);
  15.  
  16. Book b = new Book();
  17. b.setName("三国演义");
  18. b.setAuthor("罗贯中");
  19. b.setId(1);
  20. bookDao.updateBookById(b);
  21.  
  22. Book b4 = bookDao.getBookById(1);
  23. System.out.println("b4:"+b4);
  24. }
  25. }

控制台:

  1.  
  1. getBookById
  1. deleteBookById
  1. getBookById
  1. 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. 线段树+Lazy标记(我的模版)

    #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ...

  2. [C语言学习笔记二] extern 函数的用法

    extern 用来定义一个或多个变量.其后跟数据类型名和初始值.例如: extern int a =10 它与 int,long long int,double,char的本质区别,在于 extern ...

  3. java web 各个文件夹命名原因

    今天突然被同学问然后就发现,自己有很多的疑问: (1) 为什么servlet的配置文件,命名为 web.xml , 内部是如何读取的,原因就是他内度的工作原理 (2) webINF Src 文件为什么 ...

  4. [白话解析] Flink的Watermark机制

    [白话解析] Flink的Watermark机制 0x00 摘要 对于Flink来说,Watermark是个很难绕过去的概念.本文将从整体的思路上来说,运用感性直觉的思考来帮大家梳理Watermark ...

  5. Docker(三):利用Kubernetes实现容器的弹性伸缩

    一.前言 前两章有的介绍docker与Kubernetes.docker是项目运行的容器,Kubernetes则是随着微服务架构的演变docker容器增多而进行其编排的重要工具.Kubernetes不 ...

  6. Python中heapq与优先队列【详细】

    本文始发于个人公众号:TechFlow, 原创不易,求个关注 今天的文章来介绍Python当中一个蛮有用的库--heapq. heapq的全写是heap queue,是堆队列的意思.这里的堆和队列都是 ...

  7. 新来个技术总监,禁止我们使用Lombok!

    我有个学弟,在一家小型互联网公司做Java后端开发,最近他们公司新来了一个技术总监,这位技术总监对技术细节很看重,一来公司之后就推出了很多"政策",比如定义了很多开发规范.日志规范 ...

  8. js原型和原型链的简单理解

    构造函数创建对象: function Person() { } var person = new Person(); person.name = 'Tian'; console.log(person. ...

  9. Redis系列(三):Redis的持久化机制(RDB、AOF)

    本篇博客是Redis系列的第3篇,主要讲解下Redis的2种持久化机制:RDB和AOF. 本系列的前2篇可以点击以下链接查看: Redis系列(一):Redis简介及环境安装. Redis系列(二): ...

  10. FFMPEG学习----遍历所支持的封装格式

    #include <stdio.h> extern "C" { #include "libavformat/avformat.h" }; int m ...