1. 首先搭载开发环境,不会的可以参考笔者之前的文章SpringBoot入门

    添加依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
  1. 开始配置Cache

    a. 在启动类增加一个注解@EnableCaching

@SpringBootApplication
@MapperScan("com.tanoak.mapper")
@EnableCaching
public class BootCacheApplication {
​
public static void main(String[] args) {
SpringApplication.run(BootCacheApplication.class, args);
}
}
b.  pojo
@Data
public class Teacher {//使用Lombok注解 private Integer id;
private String lastName;
private String email;
​
/**
*性别 1男 0女
*/
private Integer sex;
private Integer sId;
}
c. Mapper

@Mapper
public interface TeacherMapper {
​
@Select("SELECT * FROM teacher WHERE id =#{id}")
Teacher getTeaById(Integer id);
​
@Update("UPDATE teacher SET lastName =#{lastName},email=#{email},sex=#{sex},s_id=#{sId} WHERE id=#{id}")
Integer update(Teacher teacher) ;
​
@Delete("DELETE FROM teacher WHERE id =#{id}")
Integer deleteById(Integer id) ;
​
@Insert("INSERT INTO teacher(lastName,email,sex,t_id) VALUES(#{lastName},#{email},#{sex},#{sId})")
Integer insert(Teacher teacher) ;
}
d. Service
public interface TeacherService {
​
/**
* 根据ID查询实体
* @param id
* @return
*/
​
Teacher getEmpById(Integer id) ; Integer update(Teacher teacher) ;
Integer remove(Integer id) ;
}
​
//实现类
​
@Service
public class TeacherServiceImpl implements TeacherService {
​
private static final Logger logger = LoggerFactory.getLogger(TeacherServiceImpl.class);
​
@Resource
private TeacherMapper teacherMapper ;
​
@Override
@Cacheable(cacheNames = {"emp"},condition = "#id>0")
public Teacher getEmpById(Integer id) {
logger.info("进行查询实体 ID为"+id);
return teacherMapper.getTeaById(id) ;
}
​
@Override
public Integer update(Teacher teacher) {
logger.info("修改的实体为"+teacher.toString());
return teacherMapper.update(teacher) ;
}
​
@Override
public Integer remove(Integer id) {
logger.info("删除的实体 ID为"+id);
return teacherMapper.deleteById(id) ;
}
}
e. Controller
@RestController
public class TeacherController {
​
@Resource
private TeacherService teacherService ;
​
@GetMapping("/tea/{id}")
@Cacheable(cacheNames = "tea")
public Teacher getTea(@PathVariable("id")Integer id){
return teacherService.getEmpById(id) ;
}
}
然后就开启缓存,本篇文章结束!开个玩笑,在正常的开发中,我们的CRUD需要进行缓存的环节一般是在查询,更新,删除,在一些特殊的业务场景下也会对插入进行缓存,这里不做考虑。然后我们根据需求想要解决这个问题,那么Cache对应的注解就出现了
#根据方法的请求参数对其结果进行缓存
@Cacheable
-----------
#保证方法被调用,又希望结果被缓存。
@CachePut
------------
清空缓存
@CacheEvict
了解这三个注解我们来看下如何使用吧

@Cacheable

这个注解有多个属性

key  缓存的 key 支持SpEl表达式

keyGenerator  自定义Key生成策略  二选一(key or keyGenerator)
​
condition   符合指定条件缓存
​
unless 条件为true不缓存
@Override
@Cacheable(cacheNames = "tea",key = "#id",condition = "#id>1")
public Teacher getTeaById(Integer id) {
logger.info("进行查询实体 ID为"+id);
return teacherMapper.getTeaById(id) ;
}
​
@GetMapping("/tea/{id}")
public Teacher getTea(@PathVariable("id")Integer id){
return teacherService.getEmpById(id) ;
}

自定义KeyGenerator

public class MyKeyGenerator {
​
@Bean("mykeyGenerator")
public KeyGenerator keyGenerator(){
return new KeyGenerator(){
@Override
public Object generate(Object target, Method method, Object ...params){
return method.getName() +"{"+Arrays.asList(params) +"}";
}
};
}
}

​

 @Cacheable(cacheNames = "tea",keyGenerator="mykeyGenerator")
public Teacher getTeaById(Integer id) {
logger.info("进行查询实体 ID为"+id);
return teacherMapper.getTeaById(id) ;
} ​
@GetMapping("/tea2/{id}")
public Teacher getTea2(@PathVariable("id")Integer id){
return teacherService.getTeaById(id) ;
}``` 目前解决了查询的缓存,接下来处理更新的缓存 ## @CachePut 这个注解是在方法执行完成后调用的与@Cacheable的调用顺序刚好相反

@GetMapping("/tea")

@CachePut(cacheNames = "tea")

public Teacher upTea(Teacher teacher){

teacherService.update(teacher) ;

return teacher ;

}```

可以看到,再次点击查询的时候没有发送sql语句,说明已经缓存成功

@CacheEvict

清空缓存,来认识一下

@Override
@CacheEvict(cacheNames = "tea",key = "#id")
public Integer remove(Integer id) {
logger.info("删除的实体 ID为"+id);
// return teacherMapper.deleteById(id) ;
return 1 ;
}
//然后再Controller中调用
@GetMapping("/tea3/{id}")
public String delTea(@PathVariable("id")Integer id){
teacherService.remove(id) ;
System.out.println("测试删除缓存 id为"+id);
return "OK" ;
}``` Cache的基本用法到这里就结束了,下片文章我们深入探讨它的运行机制。如理解有误,请指正

SpringBoot Cache 入门的更多相关文章

  1. springBoot从入门到源码分析

    先分享一个springBoot搭建学习项目,和springboot多数据源项目的传送门:https://github.com/1057234721/springBoot 1. SpringBoot快速 ...

  2. SpringData 基于SpringBoot快速入门

    SpringData 基于SpringBoot快速入门 本章通过学习SpringData 和SpringBoot 相关知识将面向服务架构(SOA)的单点登录系统(SSO)需要的代码实现.这样可以从实战 ...

  3. SpringBoot Docker入门,SpringBoot Docker安装

    SpringBoot Docker入门,SpringBoot Docker安装 ================================ ©Copyright 蕃薯耀 2018年4月8日 ht ...

  4. 01-项目简介Springboot简介入门配置项目准备

    总体课程主要分为4个阶段课程: ------------------------课程介绍------------------------ 01-项目简介Springboot简介入门配置项目准备02-M ...

  5. SPRING-BOOT系列之SpringBoot快速入门

    今天 , 正式来介绍SpringBoot快速入门 : 可以去如类似 https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/refer ...

  6. SpringBoot快速入门01--环境搭建

    SpringBoot快速入门--环境搭建 1.创建web工程 1.1 创建新的工程. 1.2  选择maven工程,点击下一步. 1.3 填写groupid(maven的项目名称)和artifacti ...

  7. SpringBoot 初入门

    SpringBoot 初入门 关于介绍什么之类的就不讲了,主要做一下学习记录. 1. 启动方式 IDEA 启动 命令行启动: mvn spring-boot:run 部署到服务器启动: 先进行打包, ...

  8. SpringBoot基础篇-SpringBoot快速入门

    SpringBoot基础 学习目标: 能够理解Spring的优缺点 能够理解SpringBoot的特点 能够理解SpringBoot的核心功能 能够搭建SpringBoot的环境 能够完成applic ...

  9. Springboot快速入门篇,图文并茂

    Springboot快速入门篇,图文并茂 文章已托管到GitHub,大家可以去GitHub查看阅读,欢迎老板们前来Star!搜索关注微信公众号 [码出Offer] 领取各种学习资料! image-20 ...

随机推荐

  1. 更新索引库: $locate string 寻找包含有string的路径: $updatedb

    更新索引库: $locate string 寻找包含有string的路径: $updatedb 与find不同,locate并不是实时查找.你需要更新数据库,以获得最新的文件索引信息.

  2. Linux_控制服务与守护进程

    一.systemd 1.systemd简介 1️⃣:systemd是用户空间的第一个应用程序,即/sbin/init 2️⃣:init程序的类型: SysV风格:init(centos5),实现系统初 ...

  3. Pod无法删除 强制删除pod

    多次变更服务后,发现部分pod delete僵死无法删除,一直处于Terminating状态 kubectl delete pod $pod-name一直卡住或不生效 已经删除管理资源的情况下发现仍然 ...

  4. Locust性能测试工具核心技术@task和@events

    Tasks和Events是Locust性能测试工具的核心技术,有了它们,Locust才能称得上是一个性能工具. Tasks 从上篇文章知道,locustfile里面必须要有一个类,继承User类,当性 ...

  5. [LeetCode] 1744. 你能在你最喜欢的那天吃到你最喜欢的糖果吗?

    都儿童节了,为什么要折磨一个几百个月大的孩子? 把题意读懂挺难的.不过读懂后基本也就知道怎么做了.恶心的是int类型可能会越界,要用long类型(很难想到).这题不好 [1744. 你能在你最喜欢的那 ...

  6. openresty 学习笔记番外篇:python访问RabbitMQ消息队列

    openresty 学习笔记番外篇:python访问RabbitMQ消息队列 python使用pika扩展库操作RabbitMQ的流程梳理. 客户端连接到消息队列服务器,打开一个channel. 客户 ...

  7. 重新整理 .net core 实践篇—————日志系统之战地记者[十五]

    前言 本节开始整理日志相关的东西.先整理一下日志的基本原理. 正文 首先介绍一下包: Microsoft.Extengsion.Logging.Abstrations 这个是接口包. Microsof ...

  8. CodeGen编写自定义表达式标记

    CodeGen编写自定义表达式标记 CodeGen支持开发人员通过编写plug-in modules插件模块来定义自定义表达式标记的能力,以提供与这些标记相关联的逻辑.这种plug-in module ...

  9. C#中使用swagger小技巧

    C#中使用swagger小技巧 swaggerUI显示的接口内容主要用于开发阶段便于与前端联调,不适合发布到对外的站点. 有以下两种方式,让接口不显示在SwaggerUI中 1.使用属性 [ApiEx ...

  10. H5根据浏览器内核判断并区分微信、QQ和QQ浏览器

    项目中碰到这样一个需求点,在h5页面区分当前所处客户端环境是QQ客户端.微信客户端还是QQ浏览器客户端,并做不同的逻辑处理 首先可以通过 window.navigator.userAgent 获取到当 ...