这里写目录标题
缓存介绍
缓存是一种介于永久存储介质与数据应用之间的数据临时存储介质
缓存不仅可以提供数据库的查询效率,还可以用于临时存储数据的空间
添加缓存坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
在主类开启缓存功能
@EnableCaching
重写业务层方法
使用Cacheable开启缓存操作
package com.example.service.serviceimpl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.BookDao;
import com.example.domain.book;
import com.example.service.IbookService;
import org.hibernate.annotations.Cache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.io.Serializable;
@Service
public class IbookServiceImpl extends ServiceImpl<BookDao, book>implements IbookService {
@Override
// 开启缓存操作
// 1.存储空间昵称,2.KEY:用什么查询
@Cacheable(value = "cacheSpace",key ="#id")
public book getById(Serializable id) {
return IbookService.super.getById(id); //返回值做value
}
}
取缓存中的数据
直接使用是无效的,没有走bean管理
因为Cacheable默认使用aop代理方式,通过创建内部类形式实现,而同一个类中调用无法通过代理,所以缓存不生效
@Cacheable(value = "cacheSpace",key ="#id")
public book getById(Serializable id) {
return null; //缓存中有数据就能得到,没有就返回null
}
解决办法:在当前类中注入该类的bean对象,通过当前对象的代理对象实现缓存
使用@CachePut开启缓存
在支持Spring Cache的环境下,对于使用@Cacheable标注的方法,Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。@CachePut也可以声明一个方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
@CachePut("book")//每次都会执行方法,把结果放入缓存
public User getById(Integer id) {
return null;
}
@CacheEvict 清理缓存
@CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。@CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。其中value、key和condition的语义与@Cacheable对应的属性类似。即value表示清除操作是发生在哪些Cache上的(对应Cache的名称);key表示需要清除的是哪个key,如未指定则会使用默认策略生成的key;condition表示清除操作发生的条件。下面我们来介绍一下新出现的两个属性allEntries和beforeInvocation。