1、在pom.xml中加入依赖

<!--cache-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2、在启动器上开启缓存注解

@EnableCaching

3、在需要缓存的方法上加注解

@Cacheable("userList") // 标识读缓存操作
@CachePut(cacheNames = ["user"], key = "#user.id")// 写入缓存
@CacheEvict(cacheNames = ["user"], key = "#id")// 根据 key (值为id) 来清除缓存
@Cacheable(cacheNames = ["user"], key = "#id") // 如果缓存存在,直接读取缓存值; 如果不存在调用目标方法,并将方法返回结果放入缓存

4、缓存类型

在Spring Boot中通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:

Generic
JCache (JSR-107)
EhCache 2.x
Hazelcast
Infinispan
Redis
Guava
Simple

除了按顺序侦测外,我们也可以通过配置属性spring.cache.type来强制指定。我们可以通过debug调试查看cacheManager对象的实例来判断当前使用了什么缓存。

5、把缓存改成ehcache

在src/main/resources目录下创建:ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">

    <cache name="users"
           maxEntriesLocalHeap="200"
           timeToLiveSeconds="600">
    </cache>

</ehcache>

加上依赖包

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

相关文章:

  • 2021-12-02
  • 2021-09-13
  • 2021-09-01
  • 2022-12-23
  • 2021-10-16
猜你喜欢
  • 2021-07-31
  • 2022-02-25
  • 2022-02-17
  • 2021-12-25
  • 2021-11-16
  • 2022-01-15
相关资源
相似解决方案