苍穹外卖--缓存菜品Spring Cache

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

Spring Cache提供了一层抽象,底层可以切换不同的缓存实现,例如:

①EHCache

②Caffeine

③Redis

常用注解:

代码开发:

复制代码
package com.itheima.controller;

import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping
    @CachePut(cacheNames = "userCache",key="#user.id")//如果使用Spring Cache缓存数据,key的生成:userCache::1
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }

    @DeleteMapping
    @CacheEvict(cacheNames = "userCache",key = "#id")
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }

	@DeleteMapping("/delAll")
    @CacheEvict(cacheNames = "userCache",allEntries = true)
    public void deleteAll(){
        userMapper.deleteAll();
    }

    @GetMapping
    @Cacheable(cacheNames = "userCache",key = "#id")//key的生成:userCache::10
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }

}
相关推荐
qq_165901693 分钟前
spring-cloud读取Nacos上的配置
java·spring cloud·springcloud
芒克芒克5 分钟前
深入浅出JVM的运行时数据区
java·开发语言·jvm·面试
KlayPeter7 分钟前
前端数据存储全解析:localStorage、sessionStorage 与 Cookie
开发语言·前端·javascript·vue.js·缓存·前端框架
毕设源码-赖学姐7 分钟前
【开题答辩全过程】以 影视资源分享论坛为例,包含答辩的问题和答案
java
沉默-_-9 分钟前
从小程序前端到Spring后端:新手上路必须理清的核心概念图
java·前端·后端·spring·微信小程序
xrkhy10 分钟前
多线程,高并发、物联网以及spring架构的面试题-->周
java·spring·架构
jgyzl11 分钟前
2025.12.21 学习web前必要知识点梳理
java·hash
a程序小傲14 分钟前
中国邮政Java面试被问:gRPC的HTTP/2流控制和消息分帧
java·开发语言·后端
forestsea15 分钟前
Springboot 4.0十字路口:虚拟线程时代,WebFlux与WebMVC的终极选择
java·后端·spring
Sylvia-girl18 分钟前
Java之构造方法
java·开发语言