Spring Boot 2.X整合Spring-cache(讓你的網(wǎng)站速度飛起來)
計(jì)算機(jī)領(lǐng)域有人說過一句名言:“計(jì)算機(jī)科學(xué)領(lǐng)域的任何問題都可以通過增加一個(gè)中間層來解決”,今天我們就用Spring-cache給網(wǎng)站添加一層緩存,讓你的網(wǎng)站速度飛起來。
本文目錄
一、Spring Cache介紹二、緩存注解介紹三、Spring Boot+Cache實(shí)戰(zhàn)1、pom.xml引入jar包2、啟動(dòng)類添加@EnableCaching注解3、配置數(shù)據(jù)庫(kù)和redis連接4、配置CacheManager5、使用緩存注解6、查看緩存效果7、注意事項(xiàng)
一、Spring Cache介紹
Spring 3.1引入了基于注解的緩存(cache)技術(shù),它本質(zhì)上是一個(gè)對(duì)緩存使用的抽象,通過在既有代碼中添加少量它定義的各種注解,就能夠達(dá)到緩存方法的效果。
Spring Cache接口為緩存的組件規(guī)范定義,包含緩存的各種操作集合,并提供了各種xxxCache的實(shí)現(xiàn),如RedisCache,EhCacheCache,ConcurrentMapCache等;
項(xiàng)目整合Spring Cache后每次調(diào)用需要緩存功能的方法時(shí),Spring會(huì)檢查檢查指定參數(shù)的指定的目標(biāo)方法是否已經(jīng)被調(diào)用過,如果有就直接從緩存中獲取結(jié)果,沒有就調(diào)用方法并把結(jié)果放到緩存。
二、緩存注解介紹
對(duì)于緩存聲明,Spring的緩存提供了一組java注解:
@CacheConfig:設(shè)置類級(jí)別上共享的一些常見緩存設(shè)置。
- @Cacheable:觸發(fā)緩存寫入。
- @CacheEvict:觸發(fā)緩存清除。
- @Caching 將多種緩存操作分組
- @CachePut:更新緩存(不會(huì)影響到方法的運(yùn)行)。
@CacheConfig
@CacheConfig(cacheNames = "user") @Service public class UserServiceImpl implements UserService {}
@Cacheable
- 如果key不存在,查詢db,并將結(jié)果更新到緩存中。
- 如果key存在,直接查詢緩存中的數(shù)據(jù)。
//查詢數(shù)據(jù)庫(kù)后 數(shù)據(jù)添加到緩存 @Override @Cacheable(cacheNames = "cacheManager", key = "'USER:'+#id", unless = "#result == null") public User getUser(Integer id) { return repository.getUser(id); }
@CachePut
//修改數(shù)據(jù)后更新緩存 @Override @CachePut(cacheNames = "cacheManager", key = "'USER:'+#updateUser.id", unless = "#result == null") public User updateUser(User updateUser) { return repository.save(updateUser); }
@CacheEvict
//清除一條緩存,key為要清空的數(shù)據(jù) @Override @CacheEvict(cacheNames = "cacheManager", key = "'USER:'+#id") public void deleteUser(Integer id) { repository.deleteById(id); }
三、Spring Boot+Cache實(shí)戰(zhàn)
1、pom.xml引入jar包
<!-- 引入緩存 starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- 引入 redis --> <dependency> <groupId&>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2、啟動(dòng)類添加@EnableCaching注解
@EnableCaching注解是spring framework中的注解驅(qū)動(dòng)的緩存管理功能,當(dāng)你在配置類(@Configuration)上使用@EnableCaching注解時(shí),會(huì)觸發(fā)一個(gè)post processor,這會(huì)掃描每一個(gè)spring bean,查看是否已經(jīng)存在注解對(duì)應(yīng)的緩存。如果找到了,就會(huì)自動(dòng)創(chuàng)建一個(gè)代理攔截方法調(diào)用,使用緩存的bean執(zhí)行處理。
啟動(dòng)類部分代碼如下:
3、配置數(shù)據(jù)庫(kù)和redis連接
application.properties部分配置如下:
#配置數(shù)據(jù)源信息 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://192.168.1.1:3306/test spring.datasource.username=root spring.datasource.password=1234 #配置jpa spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jackson.serialization.indent_output=true # Redis服務(wù)器地址 spring.redis.host=192.168.1.1 # database spring.redis.database = 1 # Redis服務(wù)器連接端口 使用默認(rèn)端口6379可以省略配置 spring.redis.port=6379 # Redis服務(wù)器連接密碼(默認(rèn)為空) spring.redis.password=1234 # 連接池最大連接數(shù)(如果配置<=0,則沒有限制 ) spring.redis.jedis.pool.max-active=8
4、配置CacheManager
WebConfig.java部分配置如下:
@Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { //緩存配置對(duì)象 RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) //設(shè)置緩存的默認(rèn)超時(shí)時(shí)間:30分鐘 .disableCachingNullValues() //如果是空值,不緩存 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer())) //設(shè)置key序列化器 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer()))); //設(shè)置value序列化器 return RedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); }
5、使用緩存注解
UserServiceImpl.java中使用緩存注解示例如下:
//查詢數(shù)據(jù)庫(kù)后 數(shù)據(jù)添加到緩存 @Override @Cacheable(cacheNames = "cacheManager", key = "'USER:'+#id", unless = "#result == null") public User getUser(Integer id) { return repository.getUser(id); } //清除一條緩存,key為要清空的數(shù)據(jù) @Override @CacheEvict(cacheNames = "cacheManager", key = "'USER:'+#id") public void deleteUser(Integer id) { repository.deleteById(id); } //修改數(shù)據(jù)后更新緩存 @Override @CachePut(cacheNames = "cacheManager", key = "'USER:'+#updateUser.id", unless = "#result == null") public User updateUser(User updateUser) { return repository.save(updateUser); }
6、查看緩存效果
啟動(dòng)服務(wù)后,訪問兩次http://localhost:8090/getUser/2接口,從打印日志可以看到,第一次請(qǐng)求打印了sql說明查詢了數(shù)據(jù)庫(kù),耗時(shí)960,而第二次直接查詢的緩存耗時(shí)66,增加緩存后速度提升非常明顯。
postman訪問截圖
日志截圖
7、注意事項(xiàng)
Spring cache是基于Spring Aop來動(dòng)態(tài)代理機(jī)制來對(duì)方法的調(diào)用進(jìn)行切面,這里關(guān)鍵點(diǎn)是對(duì)象的引用問題,如果對(duì)象的方法是內(nèi)部調(diào)用(即 this 引用)而不是外部引用,則會(huì)導(dǎo)致 proxy 失效,那么我們的切面就失效,也就是說上面定義的各種注釋包括 @Cacheable、@CachePut 和 @CacheEvict 都會(huì)失效。
到此Spring Boot 2.X中整合Spring-cache與Redis功能全部實(shí)現(xiàn),有問題歡迎留言溝通哦!
https://github.com/suisui2019/springboot-study
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java中處理json各種各樣的轉(zhuǎn)換方法(推薦)
下面小編就為大家分享一篇java中處理json各種各樣的轉(zhuǎn)換方法小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-11-11java實(shí)現(xiàn)簡(jiǎn)單計(jì)算器
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)單計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的示例代碼
這篇文章主要介紹了SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04在Web項(xiàng)目中手機(jī)短信驗(yàn)證碼實(shí)現(xiàn)的全過程記錄
這篇文章主要給大家介紹了關(guān)于在Web項(xiàng)目中實(shí)現(xiàn)短信驗(yàn)證碼的全過程記錄,文中通過示例代碼介紹的非常詳細(xì),在文末跟大家提供了源碼下載,需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12解決idea 項(xiàng)目編譯后沒有class文件的問題
這篇文章主要介紹了解決idea 項(xiàng)目編譯后沒有class文件的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12Java項(xiàng)目導(dǎo)出數(shù)據(jù)為 PDF 文件的操作代碼
一個(gè)小需求,需要將頁(yè)面上的數(shù)據(jù)導(dǎo)出為PDF,正常情況下這個(gè)需求需要讓前端來做,但是現(xiàn)在上面讓咱們后端來做,也沒問題,這篇文章主要介紹了Java項(xiàng)目導(dǎo)出數(shù)據(jù)為 PDF 文件的操作代碼,需要的朋友可以參考下2022-12-12SpringBoot實(shí)現(xiàn)文件上傳下載實(shí)時(shí)進(jìn)度條功能(附源碼)
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何實(shí)現(xiàn)文件上傳下載實(shí)時(shí)進(jìn)度條功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以學(xué)習(xí)一下2022-10-10