SpringBoot缓存管理默认缓存体验

1,067 阅读2分钟

在前面搭建的Web应用基础上,开启Spring Boot默认支持的缓存,体验Spring Boot默认缓存的使用效果 (1)使用@EnableCaching注解开启基于注解的缓存支持

@EnableCaching // 开启Spring Boot基于注解的缓存管理支持
@SpringBootApplication
public class Springboot04CacheApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot04CacheApplication.class, args);
}
}

(2)使用@Cacheable注解对数据操作方法进行缓存管理。将@Cacheable注解标注在Service类的查询方法上,对查询结果进行缓存

// 根据评论id查询评论信息
@Cacheable(cacheNames = "comment")
public Comment findById(int comment_id){
Optional<Comment> optional = commentRepository.findCommentById(comment_id);
if(optional.isPresent()){
return optional.get();
}
return null;
}

上述代码中,在CommentService类中的findCommentById(int comment_id)方法上添加了查询缓存注解@Cacheable,该注解的作用是将查询结果Comment存放在Spring Boot默认缓存中名称为comment的名称空间(namespace)中,对应缓存唯一标识 (即缓存数据对应的主键k)默认为方法参数comment_id的值 可以看出,再次 执行findCommentById()方法正确查询出用户评论信息Comment,在配置了Spring Boot默认注解后,重复进行同样的查询操作,数据库只执行了一次SQL查询语句,说明项目开启的默认缓存支持已经生效

  • 底层结构:在诸多的缓存自动配置类中, SpringBoot默认装配的是SimpleCacheConfiguration, 他使用的CacheManager是 ConcurrentMapCacheManager, 使用 ConcurrentMap当底层的数据结构,按照Cache的名字查询出Cache, 每一个Cache中存在多个k-v键值对,缓存值 (4)缓存注解介绍 刚刚通过使用@EnableCaching、@Cacheable注解实现了Spring Boot默认的基于注解的缓存管理,除此之外,还有更多的缓存注解及注解属性可以配置优化缓存管理 刚学了拉勾教育的《Java工程师高薪训练营》,看到刚学到的点就回答了。希望拉勾能给我推到想去的公司,目标:字节!!