0
点赞
收藏
分享

微信扫一扫

Spring Cache缓存框架

mm_tang 2023-11-07 阅读 32

1.框架介绍

spring 
spring 
CacheManager 
EhCacheCacheManager 
GuavaCacheManager 
RedisCacheManager

2.常用注解

@EnableCaching 
@Cacheable 
@CachePut 
@CacheEVict 
开 启 缓 存 注 解 功 能 
在 方 法 执 行 前 spring 先 資 看 缓 存 中 是 否 有 数 据 , 如 果 有 数 据 , 则 直 接 返 回 缓 存 数 据 ; 
若 没 有 数 据 , 调 厍 方 法 并 将 方 法 返 回 值 放 到 缓 存 中 
将 方 法 的 返 回 值 放 到 缓 存 中 
将 一 条 或 多 条 数 据 从 缓 存 中 删 除 
在 spring boot 顶 目 中 使 用 缓 存 技 术 只 需 在 顶 目 中 导 入 相 关 缓 存 技 术 的 依 赖 包 , 并 在 启 动 类 上 使 用 
@Enab 〔 a ( hing 开 启 缓 存 支 持 即 可 。 
例 如 · 使 用 Redis 作 为 缓 存 技 木 , 只 需 要 导 入 SpringdataRedisfimaven 坐 标 即 可 。

 

3.Cache框架的基本使用

不使用Redis,使用基本的缓存Manager

/**

*CachePut将方法返回值放入缓存

*value:缓存的名称,每个缓存下可以有多个key

*key:缓存的key,根据key存储缓存信息

*key的值可以使用#加字段使用方法内的返回值或者方法名,方法参数

*例如:#resul.id代表使用返回值的id属性

*#user.name代表使用方法的传入参数的name属性

*/

@CachePut(value="userCache",key="#user.id")

@PostMapping

public User save(Useruser){

userService.save(user);

return user;

}

 

/**

*将一条或者多条数据从缓存删除

*/

 

@CacheEvict(value="userCache",key="#id")

//@CacheEvict(value="userCache",key="#p0")同上等价

//@CacheEvict(value="userCache",key="#root.arge[0]")同上等价

@DeleteMapping("/{id}")

public void delete(@PathVariableLongid){

userService.removeById(id);

}

 

/**

*判断缓存中是否有数据,如果有则直接返回缓存中的数据

*condition:满足条件才进行缓存

*/

@Cacheable(value="userCache",key="#user.id",condition="#res

@PutMapping

public User update(Useruser){

userService.updateById(user);

return user;

}

 

 

4.Spring Chache 基于Redis使用

Espring BOOt1Ää *IEÆSprjng 
spring-boot-starter-data-redis. spring-boot-starter-cache 
%application.yml 
2. 
spring: 
cache : 
redi s : 
3. GE-ÜEÄ@Enablecachingu,

 

 

 

 

 

 

 

举报

相关推荐

0 条评论