當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Boot Cache之缓存
生活随笔
收集整理的這篇文章主要介紹了
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 {@AutowiredUserRepository 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);}}如果感覺不錯的話記得點贊喲!!!
總結
以上是生活随笔為你收集整理的Spring Boot Cache之缓存的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring 是什么
- 下一篇: C++ 简单计算器