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

如果覺得我的文章對您有幫助,請打賞支持。您的支持將鼓勵我繼續創作!謝謝!
微信打賞
支付寶打賞


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM