苍穹外卖--缓存菜品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;
    }

}
相关推荐
愿你天黑有灯下雨有伞5 分钟前
java动态渲染列导出以及分页列表
java
星火开发设计10 分钟前
共用体 union:节省内存的特殊数据类型
java·开发语言·数据库·c++·算法·内存
2301_8035545218 分钟前
阻塞,非阻塞,同步,异步以及linux上的5种IO模型阻塞,非阻塞,信号驱动,异步,IO复用
java·服务器·网络
仰望星空_Star30 分钟前
Java证书操作
java·开发语言
河北小博博33 分钟前
分布式系统稳定性基石:熔断与限流的深度解析(附Python实战)
java·开发语言·python
岳轩子34 分钟前
JVM Java 类加载机制与 ClassLoader 核心知识全总结 第二节
java·开发语言·jvm
h7ml42 分钟前
高并发场景下查券返利机器人的请求合并与缓存预热策略(Redis + Caffeine 实践)
数据库·redis·缓存
J_liaty43 分钟前
Spring Boot + MinIO 文件上传工具类
java·spring boot·后端·minio
2601_949613021 小时前
flutter_for_openharmony家庭药箱管理app实战+药品详情实现
java·前端·flutter
木井巳1 小时前
【递归算法】求根节点到叶节点数字之和
java·算法·leetcode·深度优先