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

}
相关推荐
疯狂吧小飞牛9 分钟前
Lua C API 中的注册表介绍
java·c语言·lua
kyle~14 分钟前
C++--- override 关键字 强制编译器验证当前函数是否重写基类的虚函数
java·前端·c++
wangmengxxw20 分钟前
Redis概述
数据库·redis·缓存
Hello.Reader23 分钟前
Flink 受管状态的自定义序列化原理、实践与可演进设计
java·网络·flink
让我上个超影吧34 分钟前
设计模式【工厂模式和策略模式】
java·设计模式·策略模式
fs哆哆1 小时前
在VB.NET中,有没有 ?.这个运算符
java·开发语言·.net
SirLancelot12 小时前
MongoDB-基本介绍(一)基本概念、特点、适用场景、技术选型
java·数据库·分布式·后端·mongodb·软件工程·软件构建
程序员小凯2 小时前
Spring Boot消息队列与事件驱动详解
java·spring boot·后端
编程岁月2 小时前
java面试-0141-java反射?优缺点?场景?原理?Class.forName和ClassLoader区别?
java·开发语言·面试
数字化顾问3 小时前
Flink ProcessFunction 与低层级 Join 实战手册:实时画像秒级更新系统
java·开发语言