ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
使用缓存的步骤如下: **1. 创建一个SpringBoot项目** ```xml <dependencies> <!-- Spring 缓存支持 --> <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> <version>1.18.24</version> </dependency> </dependencies> ``` **2. 在启动类上标注注解`@EnableCaching`开启缓存支持** ```java @EnableCaching @SpringBootApplication public class Cache01Application { public static void main(String[] args) { SpringApplication.run(Cache01Application.class, args); } } ``` **3. 在Service层中调用缓存注解** ```java @Slf4j @Service public class StudentService { /** * 如果key没有被缓存则进行缓存,方法被调用; * 如果key已被缓存则直接读取缓存,方法没有被调用; * 方法的返回值就是缓存的数据; */ @Cacheable(value = {"student"}, key = "#id") public Student get(Integer id) { log.info("get[001]:id={}", id); Student student = new Student(id, "张三", 25); return student; } /** * 更新缓存,无论某一个key是否被缓存,每次都会更新该缓存。 * 方法每次都会被调用,方法的返回值被更新到缓存中。 */ @CachePut(value = {"student"}, key = "#student.id") public Student update(Student student) { log.info("update[001]: {}", student); return student; } /** * 清除指定key的缓存. * 无论key是否存在方法都会被调用. */ @CacheEvict(value = {"student"}, key = "#id") public void delete(Integer id) { log.info("delete[001]:id={}", id); } /** * 定义复杂的缓存规则 */ @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[001]:{}", student); return student; } } ```