日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Boot Cache之缓存

發布時間:2025/3/12 javascript 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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之缓存的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。