Spring Boot 整合 Spring-cache:讓你的網站速度飛起來

計算機領域有人說過一句名言:“計算機科學領域的任何問題都可以通過增加一箇中間層來解決”,今天我們就用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查詢緩存.

  1. 如果key不存在,查詢db,並將結果更新到緩存中。

  2. 如果key存在,直接查詢緩存中的數據。

//查詢數據庫後 數據添加到緩存

@Override

@Cacheable(cacheNames = "cacheManager", key = "'USER:'+#id", unless = "#result == ")

public User getUser(Integer id) {

return repository.getUser(id);

}

@CachePut

@CachePut標註的方法在執行前不會去檢查緩存中是否存在,而是每次都會執行該方法,並將執行結果以鍵值對的形式存入指定的緩存中。

//修改數據後更新緩存

@Override

@CachePut(cacheNames = "cacheManager", key = "'USER:'+#updateUser.id", unless = "#result == ")

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包

<dependency>

<groupid>org.springframework.boot/<groupid>

<artifactid>spring-boot-starter-cache/<artifactid>

<dependency>

<groupid>org.springframework.boot/<groupid>

<artifactid>spring-boot-starter-data-redis/<artifactid>

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=63

79

# 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分鐘

.disableCachingValues //如果是空值,不緩存

.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 == ")

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 == ")

public User updateUser(User updateUser) {

return repository.save(updateUser);

}

6、查看緩存效果

啟動服務後,訪問兩次http://localhost:8090/getUser/2接口,從打印日誌可以看到,第一次請求打印了sql說明查詢了數據庫,耗時960,而第二次直接查詢的緩存耗時66,增加緩存後速度提升非常明顯。

Spring Boot 整合 Spring-cache:让你的网站速度飞起来

postman訪問截圖

Spring Boot 整合 Spring-cache:让你的网站速度飞起来

日誌截圖

7、注意事項

Spring cache是基於Spring Aop來動態代理機制來對方法的調用進行切面,這裡關鍵點是對象的引用問題,如果對象的方法是內部調用(即 this 引用)而不是外部引用,則會導致 proxy 失效,那麼我們的切面就失效,也就是說上面定義的各種註釋包括 @Cacheable、@CachePut 和 @CacheEvict 都會失效。

到此Spring Boot 2.X中整合Spring-cache與Redis功能全部實現,有問題歡迎留言溝通哦!

完整源碼地址:https://github.com/suisui2019/springboot-study


分享到:


相關文章: