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

}
相关推荐
222you4 小时前
Redis的主从复制和哨兵机制
java·开发语言
江湖有缘4 小时前
零基础入门:使用 Docker 快速部署 Organizr 个人主页
java·服务器·docker
chilavert3184 小时前
技术演进中的开发沉思-357:重排序(下)
java·后端
Boop_wu5 小时前
Spring生态
java·后端·spring
jzheng86105 小时前
Spring Boot(快速上手)
java·spring boot·后端
wgslucky5 小时前
SpringBoot解决Request和Response的内容多次读取的问题
java·spring boot·多次读取request数据
jiunian_cn5 小时前
【Redis】数据库管理操作
数据库·redis·缓存
Sylvia-girl5 小时前
IO流~~
java·开发语言
冰暮流星5 小时前
javascript之数组
java·前端·javascript
Re.不晚5 小时前
JAVA进阶之路——无奖问答挑战3
java·开发语言