SpringCache操作Redis数据库

SpringCache

概述

在这里插入图片描述
在这里插入图片描述

测试

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")       // second  1.根据形参来获取每个数据唯一标识【userCache::key作为redis中主键】
    // @CachePut(cacheNames = "userCache", key="result.id")      // second  2.根据返回值的key作为数据唯一标识
    // @CachePut(cacheNames = "userCache", key="#p0.id")         // second  3.根据特定参数访问。从零开始访问
    // @CachePut(cacheNames = "userCache", key="#a0.id")         // second  4.根据特定参数访问。同样从0开始
    @CachePut(cacheNames = "userCache", key="#root.args[0].id")  // second 5.通过root
    public User save(@RequestBody User user){                    // 注意:如果查询的id数据库中不存在就会再redis中创建以userCache::key为key,value为null的数据
        userMapper.insert(user);                                 // 此时我们再数据库中插入当前id的值,会更新缓存中的数据【将null更新为新插入数据】
        return user;                                             // 但是我们跳过程序【将null改为新数据的过程】直接修改数据库中信息并不会更新redis中数据
    }

    @GetMapping
    @Cacheable(cacheNames = "userCache", key = "#id")             // 有就加没有就查询数据库再添加到redis
    public User getById(Long id){
        User user = userMapper.getById(id);               // 如果查询的id存在于redis中就不会执行这个方法
        return user;                                      // 因为SpringCache会为当前Controller创建一个代理对象,请求这个
    }                                                     // 代理对象,再代理对象中查询redis,有数据就直接返回。如果将redis中
                                                          // 这条数据删除掉就会执行该方法查询数据库中信息
    @DeleteMapping
    @CacheEvict(cacheNames = "userCache", key = "#id")    // 清理缓存,开始就执行还是sql正常执行后执行呢?【先删除数据库信息再删除redis中信息】
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }

	@DeleteMapping("/delAll")
    @CacheEvict(cacheNames = "userCache", allEntries= true)     // 设置当前层的所有数据
    public void deleteAll(){                                    // 对于删除操作都是先删除数据库数据,再删除缓存数据
        userMapper.deleteAll();
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值