当前位置: 首页 > article >正文

使用springCache实现缓存

简介

这个springCache貌似jdk8或者以上才可以

  • cache最好加在controller层,毕竟返回给前端的数据,在这一步才是最完整的,缓存controller的数据才有意义

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

配置

导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

@EnableCaching // 开启缓存注解

@Slf4j
@SpringBootApplication
@EnableCaching // 开启缓存注解
public class CacheDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheDemoApplication.class,args);
        log.info("项目启动成功...");
    }
}

配置一下redis

server:
  port: 8888
spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/spring_cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: root
      password: root
  redis:
    host: localhost
    port: 6379
    database: 1

注解CachePut

key有两种写法

    @PostMapping
    @CachePut(cacheNames = "userCache",key = "#user.id") // 更新缓存 key的生成是 userCache::id 形参user.id
//    @CachePut(cacheNames = "userCache",key = "#result.id") // 更新缓存 key的生成是 userCache::id 返回值id
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }

注解@Cacheable

查询缓存 key的生成是 userCache::id)(如果有缓存则直接返回缓存,没有则查询数据库,然后将查询结果缓存)

    @GetMapping
    @Cacheable(cacheNames = "userCache",key = "#id") // 查询缓存 key的生成是 userCache::id)(如果有缓存则直接返回缓存,没有则查询数据库,然后将查询结果缓存)
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }

注解@CacheEvict

分为删除一个和删除所有

    @DeleteMapping
    @CacheEvict(cacheNames = "userCache",key = "#id") // 删除缓存 key是 userCache::id
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }

	@DeleteMapping("/delAll")
    @CacheEvict(cacheNames = "userCache",allEntries = true) // 删除缓存 key是 userCache::id
    public void deleteAll(){
        userMapper.deleteAll();
    }

http://www.kler.cn/news/342434.html

相关文章:

  • 新媒体运营重点
  • 2_互联网概述_20241007
  • CSS响应式布局
  • Apache DolphinScheduler-1.3.9源码分析(二)
  • Go 语言应用开发:从入门到实战
  • 2024年软件设计师中级(软考中级)详细笔记【3】数据结构(下)(分值5分)
  • HTML 之 <div> 和 <span>
  • 【高等代数笔记】线性空间(二十四下半部分-二十六)
  • axios 使用
  • ECCV`24 | 新加坡国立华为提出Vista3D: 实现快速且多视角一致的3D生成
  • SCRM呼叫中心高保真Axure原型 源文件分享
  • 基于IOU匹配的DeepSort目标跟踪与匈牙利算法解析
  • QFontComboBox Class
  • 初识Linux操作系统与Shell命令
  • ARM base instruction -- umull
  • [vscode]格式化C#代码
  • 鸿蒙开发(NEXT/API 12)【HTTP数据请求】网络篇
  • oracle set命令
  • 澳鹏干货 | 大语言模型的上下文窗口 (Context Windows)
  • 使用 Go 语言与 Redis 构建高效缓存与消息队列系统