Spring Boot 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<User>,现在你执行了一个 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;

/**
 * 接口实现
 */
@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);
  }

}

如果感觉不错的话记得点赞哟!!!

发布了273 篇原创文章 · 获赞 91 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_45743799/article/details/104362123