springboot系列:使用缓存

2022-10-16,,

前言:springboot已经为我们实现了抽象的api接口,因此当我们使用不同的缓存时,只是配置有可能有点区别(比如ehcache和redis),但是在程序中使用缓存的方法是一样的。

 

1.springboot使用ehcache缓存

1.步骤:   

1.在pom.xml中配置2个依赖,添加spring-boot-starter-cache启动器,以及ehcache。

  <!-- ehcache -->
  <dependency>
    <groupid>net.sf.ehcache</groupid>
    <artifactid>ehcache</artifactid>
    <version>2.10.4</version>
  </dependency>

  <!-- 缓存支持启动器 -->
  <dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-cache</artifactid>
  </dependency>

2.在resources目录下创建ehcache.xml配置文件。

  ehcache.xml配置文件格式如下(该配置文件没有文档约束):

  <ehcache>

 

    <diskstore path="java.io.tmpdir"/>

    <defaultcache
      maxelementsinmemory="10000"
      eternal="false"
      timetoidleseconds="120"
      timetoliveseconds="120"
      overflowtodisk="true"
    />

    <cache name="samplecache1"
      maxelementsinmemory="10000"
      eternal="false"
      timetoidleseconds="300"
      timetoliveseconds="600"
      overflowtodisk="true"
    />

  <ehcache>
3.在application.properties文件中指定ehcache的配置文件ehcache.xml,设置spring.cache.ehcache.config=ehcache.xml。

  spring.cache.ehcache.config=ehcache.xml
4.在主类上添加自动配置并启动缓存的注解@enablecaching。

5.在类上配置缓存策略(通常在service层)。

  @cacheconfig:配置用于指定ehcache.xml文件配置的缓存策略;该注解用在类上。

  @cacheable:存取缓存;主要用在查找方法上。

  @cacheput:修改缓存,如果不存在就创建;主要用在修改方法上。

  @cacheevict:删除缓存,当数据删除时,如果缓存还在,就必须删除;主要用在删除方法上。

  注意:缓存的pojo类需要实现序列化

《springboot系列:使用缓存.doc》

下载本文的Word格式文档,以方便收藏与打印。