🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
使用缓存的步骤如下: **1. 引入 spring-boot-starter-cache** ```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>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> ``` <br/> **2. 在启动类上标注注解`@EnableCaching`开启缓存支持** ```java @EnableCaching @SpringBootApplication public class CacheApplication { public static void main(String[] args) { SpringApplication.run(CacheApplication.class, args); } } ``` <br/> **3. 在类或方法上调用缓存注解** ```java @Slf4j @Service public class StudentServiceImpl implements StudentService { /** * 如果key没有被缓存则进行缓存,方法被调用; * 如果key已被缓存则直接读取缓存,方法没有被调用; * 方法的返回值就是缓存的数据; */ @Override @Cacheable(value = {"student"}, key = "#id") public Student get(Integer id) { log.info("[get|id]: {}", id); Student student = new Student(id, "张三", 25); return student; } /** * 更新缓存,无论某一个key是否被缓存,每次都会更新该缓存。 * 方法每次都会被调用,方法的返回值被更新到缓存中。 */ @Override @CachePut(value = {"student"}, key = "#student.id") public Student update(Student student) { log.info("[update|student]: {}", student); return student; } /** * 清除指定key的缓存. * 无论key是否存在方法都会被调用. */ @Override @CacheEvict(value = {"student"}, key = "#id") public void delete(Integer id) { log.info("[delete|id]:{}", id); } /** * 定义复杂的缓存规则 */ @Override @Caching( cacheable = { @Cacheable(value = "student", key = "#student.id") }, put = { @CachePut(value = "student", key = "#result.id", condition = "#student.id == 2"), } ) public Student getOrUpdate(Student student) { log.info("[getOrUpdate|student]:{}", student); return student; } } ``` ```java //将缓存注解标注在接口的方法上也是可以的 public interface StudentService { @Cacheable(value = {"student"}, key = "#id") Student get(Integer id); @CachePut(value = {"student"}, key = "#student.id") Student update(Student student); } ```