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

}
相关推荐
程序猿阿越4 分钟前
Kafka源码(三)发送消息-客户端
java·后端·源码阅读
whitepure10 分钟前
万字详解Java中的运算
java
AAA修煤气灶刘哥11 分钟前
搞定 Redis 不难:从安装到实战的保姆级教程
java·redis·后端
MrSYJ14 分钟前
全局和局部AuthenticationManager
java·后端·程序员
界面开发小八哥19 分钟前
「Java EE开发指南」如何使用MyEclipse中的Web Fragment项目?
java·ide·java-ee·eclipse·myeclipse
青鱼入云20 分钟前
redis怎么做rehash的
redis·缓存
FFF-X42 分钟前
Vue3 路由缓存实战:从基础到进阶的完整指南
vue.js·spring boot·缓存
Tadas-Gao1 小时前
Java设计模式全景解析:从演进历程到创新实践
java·开发语言·微服务·设计模式·云原生·架构·系统架构
励志成为架构师1 小时前
跟小白一起领悟Thread——如何开启一个线程(上)
java·后端