Spring Cache

Spring Cache

1、Spring Cache 介绍

Spring Cache 是一个框架,实现了基于注解的缓存功能,只需要简单的加一个注解,就能实现缓存功能。

Spring Cache 提供一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager 接口来统一不同的缓存技术

CacheManager 是spring 提供的各种缓存技术的抽象接口

image-20230108164316148

2、Spring Cache 常用注解

注解 说明
@EnableCaching 开启缓存注解功能
@Cacheable 在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回数据;若没有数据,调用方法并将方法返回值放进缓存中。
@CachePut 将方法的返回值放入缓存中
@CacheEvict 将一条或多条数据从缓存中删除

在spring boot 项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类使用@EnableCaching开启缓存支持即可

例如,使用Redis作为缓存技术,只需要导入Spring data Redis 的maven坐标即可

3、注解使用 (返回结果的类必须实现 Serializeable 接口)

CachePut:通常用于新增数据时刻

/**
* value: 缓存的名称,每个缓存名称下面有多个key
* key:缓存的key 可以使用 #result.id 代表的是返回值的user的id,也可以使用#root,method代表使用方法名,还可以使用#user.name代表使用参数的name属性
*/
@Cacheput(value = "userCache", key = "#user.name")
@PostMapping
public User save(User user){
    userService.save(user);
    return user;
}

CacheEvict :通常用于删除和修改数据时刻

// 删除数据
@CacheEvict(value = "userCache", key = "#id")
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
    userService.removeById(id);
}

// 修改数据
@CacheEvict(value = "userCache", key = "#user.id")
@PostMapping
public User update(User user){
    userService.updateById(id);
    return user;
}

Cacheable:通常用于查找数据时刻

// condition 表示 返回结果不为null的时候在加入缓存,若为null则不加入缓存
@Cacheable(value = "userCache", key = "#id", condition = "#result != null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
    return userService.getById(id);
}

4、使用Redis缓存技术

  1. 导入maven坐标
    spring-boot-starter-data-redis、spring-boot-starter-cache

  2. 配置application.yml

    spring:
    	cache:
    		redis:
    			time-to-live: 1800000 # 设置缓存有效期
    
  3. 在启动类上加上@EnableCaching 注解,开启缓存功能

  4. 在Controller的方法上加入@Cacheable等注解,进行缓存操作

posted @   Freshman0611  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示