Spring Cache【娓娓道来】

目录​​​​​​​

1.自我介好😳😳😳

[2.常用注解 💕💕💕](#2.常用注解 💕💕💕)

3.@EnableCaching🤦‍♂️🤦‍♂️🤦‍♂️

4.@CachePut🤷‍♀️🤷‍♀️🤷‍♀️

5.@CacheEvict🎶🎶🎶

[6.@Cacheable 🤩🤩🤩](#6.@Cacheable 🤩🤩🤩)


1.自我介好😳😳😳

Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。Spring Cache提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。

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

2.常用注解 💕💕💕

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

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

3.@EnableCaching🤦‍♂️🤦‍♂️🤦‍♂️

@EnableCaching 是启用缓存的注解,标注在任何一个可自动注入的类上即可开启。

java 复制代码
@Slf4j
@SpringBootApplication
@EnableCaching
public class SpirngbootReidsApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpirngbootReidsApplication.class, args);
    }

}

4.@CachePut🤷‍♀️🤷‍♀️🤷‍♀️

  • @CachePut将方法的返回值放到缓存中

value:缓存的名称,每个缓存下面有多个key

key:缓存的key

java 复制代码
 @CachePut(value = "userCache",key = "#result.userId")
    @PostMapping
    public User save(@RequestBody User user){
        userService.save(user);
        return user;
    }

5.@CacheEvict🎶🎶🎶

  • @CacheEvict将一条或多条数据从缓存中删除

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

key:缓存key

删除

java 复制代码
 @CacheEvict(value = "userCache", key = "#id")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id") Integer id) {
        userService.removeById(id);
    }

修改

java 复制代码
  @CacheEvict(value = "userCache",key = "#user.userId")
    @PutMapping
    public User update(@RequestBody User user) {
        userService.updateById(user);
        return user;
    }

6.@Cacheable 🤩🤩🤩

  • @Cacheable在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中

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

key:缓存key

condition:条件,满足条件时才缓存数据

unless: 满足条件,不缓存

java 复制代码
   @Cacheable(value = "userCache", key = "#id", condition = "#result!=null")
    @GetMapping(value = "/{id}")
    public User get(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        return user;
    }
java 复制代码
  @Cacheable(value = "userCache", key = "#id", unless = "#result==null")
    @GetMapping(value = "/{id}")
    public User get(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        return user;
    }

相关推荐
亓才孓13 小时前
[JDBC]事务
java·开发语言·数据库
Victor35613 小时前
Hibernate(91)如何在数据库回归测试中使用Hibernate?
后端
CHU72903513 小时前
直播商城APP前端功能全景解析:打造沉浸式互动购物新体验
java·前端·小程序
Victor35613 小时前
MongoDB(1)什么是MongoDB?
后端
侠客行031720 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪20 小时前
深入浅出LangChain4J
java·langchain·llm
Victor35620 小时前
https://editor.csdn.net/md/?articleId=139321571&spm=1011.2415.3001.9698
后端
Victor35620 小时前
Hibernate(89)如何在压力测试中使用Hibernate?
后端
灰子学技术1 天前
go response.Body.close()导致连接异常处理
开发语言·后端·golang
老毛肚1 天前
MyBatis体系结构与工作原理 上篇
java·mybatis