zoukankan      html  css  js  c++  java
  • springboot缓存之@CachePut注解

    接上一节。

    @CachePut:既调用方法,又更新缓存。

    使用场景:当更改了数据库的某个数据,同时也更新缓存。

    运行时机:先调用目标方法,然后将结果放入缓存。

    package com.gong.springbootcache.controller;
    
    import com.gong.springbootcache.bean.Employee;
    import com.gong.springbootcache.service.EmployeeService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    public class EmployeeController {
    
        @Autowired
        EmployeeService employeeService;
    
        //value:指定缓存的名字,每个缓存组件有一个唯一的名字。缓存组件由CacheManager进行管理。
        //key:缓存数据时用到的key,默认使用方法参数的值,1-方法返回值 key =
        //#id也可这么表示:#root.args[0](第一个参数)
        //keyGenerator:指定生成缓存的组件id,使用key或keyGenerator其中一个即可
        //cacheManager,cacheResolver:指定交由哪个缓存管理器,使用其中一个参数即可
        //condition:指定符合条件时才进行缓存
        //unless:当unless指定的条件为true,方法的返回值就不会被缓存
        //sync:是否使用异步模式
        //"#root.methodName+'[+#id+]'"
        @Cacheable(value = "emp")
        @ResponseBody
        @RequestMapping("/emp/{id}")
        public Employee getEmp(@PathVariable("id") Integer id){
            Employee emp = employeeService.getEmp(id);
            return emp;
        }
    
        @CachePut(value = "emp")
        @GetMapping("/emp")
        public Employee updateEmp(Employee employee){
            Employee emp =  employeeService.updateEmp(employee);
            return emp;
        }
    }

    第一次查询:

    没有使用缓存。

    第二次查询:使用到了缓存,不必再发送sql。

    然后进行更新:

    先执行了方法,也就是会发送sql:

    然后我们再执行一次查询:

    此时我们查询出来的是从缓存中获取的,但是,为什么缓存没有进行更新呢?

    这是因为getEmp中参数为id,updateEmp参数中为employee。我们知道,如果使用缓存时不指定缓存的key,也就是设置key或者keyGenerator属性,那么,缓存的key就是方法中参数的组合,所以,若果要实现同步的话,我们要指定缓存的key为相同的值。

    我们只需要将updateEmp方法中的CachePut注解中加上:key="#employee.id"。

    此时再按照之前的步骤再来一次,记得先把2号员工的数据先改回去,在修改后再进行查询:

    得到了我们想要的值,同时也没有发送sql。 

  • 相关阅读:
    致远OA-A8协同管理软件无需登录getshell漏洞
    WordPress插件NextGEN Gallery <= 3.2.2 RCE漏洞利用(需要登录)
    Coremail邮件系统配置文件泄露漏洞
    CVE-2019-12735 VIM命令执行漏洞利用
    分享一个乌云Drops文章在线浏览的网站
    Ubuntu、Debian安装Docker CE
    一些好用的网络渗透工具和查询平台
    CVE-2017-11882 Office内存损坏漏洞利用
    Cobalt Strike入门教程-通过exe木马实现远控
    Jfinal cms前台评论XSS漏洞分析
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12290877.html
Copyright © 2011-2022 走看看