苍穹外卖--缓存菜品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_4376643145 分钟前
C++11 右值引用 Lambda 表达式
java·开发语言·c++
永卿0016 分钟前
设计模式-迭代器模式
java·设计模式·迭代器模式
誰能久伴不乏14 分钟前
Linux如何执行系统调用及高效执行系统调用:深入浅出的解析
java·服务器·前端
慕y27436 分钟前
Java学习第七十二部分——Zookeeper
java·学习·java-zookeeper
midsummer_woo40 分钟前
基于spring boot的医院挂号就诊系统(源码+论文)
java·spring boot·后端
_Aaron___1 小时前
面向对象的三大特性---多态
java
Kiri霧1 小时前
IntelliJ IDEA
java·ide·kotlin·intellij-idea
daixin88482 小时前
什么是缓存雪崩?缓存击穿?缓存穿透?分别如何解决?什么是缓存预热?
java·开发语言·redis·缓存
京茶吉鹿2 小时前
"if else" 堆成山?这招让你的代码优雅起飞!
java·后端
你我约定有三2 小时前
RabbitMQ--消息丢失问题及解决
java·开发语言·分布式·后端·rabbitmq·ruby