• SpringBoot缓存使用方式@EnableCaching、@Cacheable


    目录

    一 缓存简介

    二 spring缓存使用方式

    三 代码    

    1 添加依赖

    2 启用缓存

    3 设置进入缓存的数据


    一 缓存简介

    缓存 是一种介于数据永久存储介质(数据库)与数据应用(程序)之间的数据临时存储介质

    目的:
    1 减少低速数据读取过程的次数(例如磁盘IO),提高系统性能
    2 不仅可以提高永久性存储介质的数据读取效率,还可以提供临时的数据存储空间.

    二 spring缓存使用方式

    实现效果:当第1次查询数据时从数据库里读数据,当第2次查询相同的数据时,直接从缓存里读数据.

    步骤:
    1 添加依赖
    2 启用缓存:引导类上加注解@EnableCaching
    3 设置进入缓存的数据
        serviceImpl方法上添加@Cacheable(key = "#id",value = "cacheSpace")

    三 代码    

    1 添加依赖

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-cache</artifactId>
    4. </dependency>


    2 启用缓存

    引导类上加注解@EnableCaching

    3 设置进入缓存的数据


        serviceImpl方法上添加@Cacheable(key = "#id",value = "cacheSpace")

    1. package com.qing.service.impl;
    2. import com.qing.bean.Book;
    3. import com.qing.dao.BookDao;
    4. import com.qing.service.BookService;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.cache.annotation.Cacheable;
    7. import org.springframework.stereotype.Service;
    8. import java.util.List;
    9. @Service
    10. public class BookServiceImpl implements BookService {
    11. @Autowired
    12. private BookDao bookDao;
    13. @Override
    14. @Cacheable(key = "#id",value = "cacheSpace")
    15. public Book getById(Integer id) {
    16. return bookDao.selectById(id);
    17. }
    18. }

    把缓存想象成一个hashmap,@Cacheable的属性key就是hashmap的key,value就是hashmap的value

    controller

    1. package com.qing.controller;
    2. import com.qing.bean.Book;
    3. import com.qing.service.BookService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.PathVariable;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.RestController;
    9. @RestController
    10. @RequestMapping("/books")
    11. public class BookController {
    12. @Autowired
    13. BookService bookService;
    14. @GetMapping("/{id}")
    15. public String getById(@PathVariable Integer id){
    16. Book book = bookService.getById(id);
    17. return book.toString();
    18. }
    19. }

    测试

     第一次查id=12,走数据库

     第二次查id=12,走缓存,不走数据库

     第一次查id=14,走数据库

      第三次查id=12,走缓存,不走数据库

    总结

     

     

  • 相关阅读:
    PWA 应用 Service Worker 缓存的一些可选策略和使用场景
    【设计模式】【创建型5-4】【建造者模式】
    JavaScript对象
    蓝桥杯国奖一等奖,经历回顾
    SpringSecurity OAuth2 配置 token有效时长
    15. Redis 持久化
    力扣刷题学习SQL篇——1-10 选择(丢失信息的雇员——合并两个表的相同列union all)
    Redis 命令—— 超详细操作演示!!!
    转守为攻,亚马逊云换帅背后的战略转向
    Java中方法的定义及注意事项
  • 原文地址:https://blog.csdn.net/m0_45877477/article/details/125525987