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

目录

一 缓存简介

二 spring缓存使用方式

三 代码    

1 添加依赖

2 启用缓存

3 设置进入缓存的数据


一 缓存简介

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

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

二 spring缓存使用方式

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

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

三 代码    

1 添加依赖

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


2 启用缓存

引导类上加注解@EnableCaching

3 设置进入缓存的数据


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

package com.qing.service.impl;

import com.qing.bean.Book;
import com.qing.dao.BookDao;
import com.qing.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

   
    @Override
    @Cacheable(key = "#id",value = "cacheSpace")
    public Book getById(Integer id) {
        return bookDao.selectById(id);
    }

   
}

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

controller

package com.qing.controller;

import com.qing.bean.Book;
import com.qing.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;


@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    BookService bookService;

    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        Book book = bookService.getById(id);
        return book.toString();
    }
}

测试

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

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

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

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

总结

 

 

猜你喜欢

转载自blog.csdn.net/m0_45877477/article/details/125525987