当前位置 博文首页 > 刘信坚的博客:SpringBoot与缓存使用及原理(下)

    刘信坚的博客:SpringBoot与缓存使用及原理(下)

    作者:[db:作者] 时间:2021-08-11 19:20

    这次的博客文章是基于上一篇博客?SpringBoot与缓存使用及原理(上)?


    一 环境准备

    pom.xml文件中导入spring-boot-starter-cache,我这里是使用了redis做为缓存

    <dependencies>
    ???<dependency>
    ??????<groupId>org.springframework.boot</groupId>
    ??????<artifactId>spring-boot-starter-cache</artifactId>
    ???</dependency>
    ???<dependency>
    ??????<groupId>org.springframework.boot</groupId>
    ??????<artifactId>spring-boot-starter-web</artifactId>
    ???</dependency>
    </dependencies>
    

    https://img4.mukewang.com/5b213d550001030209250794.jpg

    二 Spring-boot-starter-cache运行流程

    今天我们来探索下SpringBoot中的缓存原理,首先我们看看pom.xml文件

    https://img.mukewang.com/5b213b3b0001aff211480359.jpg??

    可以看到我用的spring-boot-starter-cache是 1.5.13.RELEASE,接着看下maven导入的配置

    https://img4.mukewang.com/5b213e320001efe907550816.jpg

    https://img4.mukewang.com/5b213fb70001779315760711.jpg

    每次启动项目的时候Springboot会自动为我们导入

    org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
    

    在org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration中可以看到

    https://img.mukewang.com/5b2142c50001daa615290815.jpg

    https://img2.mukewang.com/5b2143a200019a5e13710724.jpg

    https://img1.mukewang.com/5b2143f60001b9d610790524.jpg

    https://img.mukewang.com/5b21455000015e3914290437.jpg

    https://img3.mukewang.com/5b21460d0001a1c215790737.jpg


    接下来开始debug:

    https://img3.mukewang.com/5b21483d0001bc6415710619.jpg

    https://img3.mukewang.com/5b214ca20001a46a15750736.jpg

    https://img4.mukewang.com/5b2150630001923f13200745.jpg

    https://img.mukewang.com/5b2150bb0001989510870510.jpg

    继续debug下去

    https://img3.mukewang.com/5b2151570001c4a713080534.jpg

    https://img4.mukewang.com/5b215197000154af18490237.jpg

    https://img4.mukewang.com/5b21522f00017a0415450238.jpg

    https://img1.mukewang.com/5b21527500019ec717420283.jpg

    https://img1.mukewang.com/5b2152ce0001508d15500219.jpg

    这时控制台打印出了从数据库中获取的数据:

    https://img1.mukewang.com/5b2152f80001fe7618550164.jpg

    再来发送一次请求?http://localhost:8080/emp/1

    https://img.mukewang.com/5b21532700010b6613950170.jpg

    https://img2.mukewang.com/5b2154010001c24f14610550.jpg

    可以看到第二次从缓存中获取数据,并且将缓存数据进行返回

    https://img.mukewang.com/5b21549a0001319613090872.jpg

    https://img.mukewang.com/5b21550e0001661e17840744.jpg

    https://img2.mukewang.com/5b2155ac0001bc9716970716.jpg

    然后下面就正式开始执行目标方法了

    https://img4.mukewang.com/5b2155e80001406217630261.jpg

    到这里就可以发现,没有去走service调用数据库的那条路线,后面的方法就是一些代理及转发等操作,spring底层原理相关就不看源码了。

    三 总结

    ? ? ?Spring-boot-starter-cache的基本的运行流程的源码就过了一遍,可能有些源码没有截图出来,不会的朋友可以一定要自己亲自去debug,这样会更加有理解源码的思维和提升自己看代码的能力,我也是学习阶段,可能存在很多不足,有问题还望大家指出,谢谢大家。


    cs