計算機領域有人說過一句名言:“計算機科學領域的任何問題都可以通過增加一個中間層來解決”,今天我們就用Spring-cache給網站添加一層緩存,讓你的網站速度飛起來。
本文目錄
一、Spring Cache介紹二、緩存注解介紹三、Spring Boot+Cache實戰1、pom.xml引入jar包2、啟動類添加@EnableCaching注解3、配置數據庫和redis連接4、配置CacheManager5、使用緩存注解6、查看緩存效果7、注意事項
一、Spring Cache介紹
Spring 3.1引入了基於注解的緩存(cache)技術,它本質上是一個對緩存使用的抽象,通過在既有代碼中添加少量它定義的各種注解,就能夠達到緩存方法的效果。
Spring Cache接口為緩存的組件規范定義,包含緩存的各種操作集合,並提供了各種xxxCache的實現,如RedisCache,EhCacheCache,ConcurrentMapCache等;
項目整合Spring Cache后每次調用需要緩存功能的方法時,Spring會檢查檢查指定參數的指定的目標方法是否已經被調用過,如果有就直接從緩存中獲取結果,沒有就調用方法並把結果放到緩存。
二、緩存注解介紹
對於緩存聲明,Spring的緩存提供了一組java注解:
- @CacheConfig:設置類級別上共享的一些常見緩存設置。
- @Cacheable:觸發緩存寫入。
- @CacheEvict:觸發緩存清除。
- @Caching 將多種緩存操作分組
- @CachePut:更新緩存(不會影響到方法的運行)。
@CacheConfig
該注解是可以將緩存分類,它是類級別的注解方式。我們可以這么使用它。
這樣的話,UserServiceImpl的所有緩存注解例如@Cacheable的value值就都為user。
@CacheConfig(cacheNames = "user")
@Service
public class UserServiceImpl implements UserService {}
@Cacheable
一般用於查詢操作,根據key查詢緩存.
- 如果key不存在,查詢db,並將結果更新到緩存中。
- 如果key存在,直接查詢緩存中的數據。
//查詢數據庫后 數據添加到緩存
@Override
@Cacheable(cacheNames = "cacheManager", key = "'USER:'+#id", unless = "#result == null")
public User getUser(Integer id) {
return repository.getUser(id);
}
@CachePut
@CachePut標注的方法在執行前不會去檢查緩存中是否存在,而是每次都會執行該方法,並將執行結果以鍵值對的形式存入指定的緩存中。
//修改數據后更新緩存
@Override
@CachePut(cacheNames = "cacheManager", key = "'USER:'+#updateUser.id", unless = "#result == null")
public User updateUser(User updateUser) {
return repository.save(updateUser);
}
@CacheEvict
根據key刪除緩存中的數據。allEntries=true表示刪除緩存中的所有數據。
//清除一條緩存,key為要清空的數據
@Override
@CacheEvict(cacheNames = "cacheManager", key = "'USER:'+#id")
public void deleteUser(Integer id) {
repository.deleteById(id);
}
三、Spring Boot+Cache實戰
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注解時,會觸發一個post processor,這會掃描每一個spring bean,查看是否已經存在注解對應的緩存。如果找到了,就會自動創建一個代理攔截方法調用,使用緩存的bean執行處理。
啟動類部分代碼如下:
@SpringBootApplication
@EnableCaching
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3、配置數據庫和redis連接
application.properties部分配置如下:
#配置數據源信息
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
# 連接池最大連接數(如果配置<=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中使用緩存注解示例如下:
//查詢數據庫后 數據添加到緩存
@Override
@Cacheable(cacheNames = "cacheManager", key = "'USER:'+#id", unless = "#result == null")
public User getUser(Integer id) {
return repository.getUser(id);
}
//清除一條緩存,key為要清空的數據
@Override
@CacheEvict(cacheNames = "cacheManager", key = "'USER:'+#id")
public void deleteUser(Integer id) {
repository.deleteById(id);
}
//修改數據后更新緩存
@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說明查詢了數據庫,耗時960,而第二次直接查詢的緩存耗時66,增加緩存后速度提升非常明顯。

postman訪問截圖

日志截圖
7、注意事項
Spring cache是基於Spring Aop來動態代理機制來對方法的調用進行切面,這里關鍵點是對象的引用問題,如果對象的方法是內部調用(即 this 引用)而不是外部引用,則會導致 proxy 失效,那么我們的切面就失效,也就是說上面定義的各種注釋包括 @Cacheable、@CachePut 和 @CacheEvict 都會失效。
到此Spring Boot 2.X中整合Spring-cache與Redis功能全部實現,有問題歡迎留言溝通哦!
完整源碼地址: https://github.com/suisui2019/springboot-study
推薦閱讀
1.Spring Boot 2.X 整合Redis
2.Spring Boot 2.X 如何優雅的解決跨域問題?
3.Spring Boot 2.X 集成spring session實現session共享
4.Spring條件注解@Conditional
5.SpringBoot 2.X從0到1實現郵件發送功能
6.Redis批量刪除key的小技巧,你知道嗎?
7.Spring Boot 2.X 如何快速整合jpa?
8.Spring Boot之Profile--快速搞定多環境使用與切換
9.Spring Boot快速集成kaptcha生成驗證碼
限時領取免費Java相關資料,涵蓋了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高並發分布式、大數據、機器學習等技術。
關注下方公眾號即可免費領取:
