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