Spring Boot 系列教程17-Cache-缓存

缓存

  • 缓存就是数据交换的缓冲区(称作Cache),当某一硬件要读取数据时,会首先从缓存中查找需要的数据,如果找到了则直接执行,找不到的话则从内存中找。由于缓存的运行速度比内存快得多,故缓存的作用就是帮助硬件更快地运行。
  • 因为缓存往往使用的是RAM(断电即掉的非永久储存),所以在用完后还是会把文件送到硬盘等存储器里永久存储。电脑里最大的缓存就是内存条了,最快的是CPU上镶的L1和L2缓存,显卡的显存是给显卡运算芯片用的缓存,硬盘上也有16M或者32M的缓存。

Spring3.1开始引入了对Cache的支持

  • 其使用方法和原理都类似于Spring对事务管理的支持,就是aop的方式。
    Spring Cache是作用在方法上的,其核心思想是:当我们在调用一个缓存方法时会把该方法参数和返回结果作为一个键值对存放在缓存中,等到下次利用同样的参数来调用该方法时将不再执行该方法,而是直接从缓存中获取结果进行返回。

@CacheConfig

  • * 在类上面统一定义缓存的名字,方法上面就不用标注了*
  • * 当标记在一个类上时则表示该类所有的方法都是支持缓存的*

@CachePut

  • * 根据方法的请求参数对其结果进行缓存*
  • * 和 @Cacheable 不同的是,它每次都会触发真实方法的调用*
  • * 一般可以标注在save方法上面*

@CacheEvict

  • * 针对方法配置,能够根据一定的条件对缓存进行清空*
  • * 一般标注在delete,update方法上面*

Spring Cache现有缺陷

  • 如有一个缓存是存放 List,现在你执行了一个 update(user)的方法,你一定不希望清除整个缓存而想替换掉update的元素
  • 这个在现有缓存实现上面没有很好的方案,只有每次dml操作的时候都清除缓存,配置如下@CacheEvict(allEntries=true)

UserServiceImpl

package com.jege.spring.boot.data.jpa.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jege.spring.boot.data.jpa.entity.User;
import com.jege.spring.boot.data.jpa.repository.UserRepository;
import com.jege.spring.boot.data.jpa.service.UserService;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:业务层接口实现
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {
  @Autowired
  UserRepository userRepository;

  @Override
  @Cacheable()
  public Page<User> findAll(Pageable pageable) {
    return userRepository.findAll(pageable);
  }

  @Override
  @Cacheable()
  public Page<User> findAll(Specification<User> specification, Pageable pageable) {
    return userRepository.findAll(specification, pageable);
  }

  @Override
  @Transactional
  @CacheEvict(allEntries=true)
  public void save(User user) {
    userRepository.save(user);
  }

  @Override
  @Transactional
  @CacheEvict(allEntries=true)
  public void delete(Long id) {
    userRepository.delete(id);
  }

}

其他关联项目

源码地址

https://github.com/je-ge/spring-boot

如果觉得我的文章对您有帮助,请打赏支持。您的支持将鼓励我继续创作!谢谢!
微信打赏
支付宝打赏

原文地址:https://www.cnblogs.com/je-ge/p/6138975.html