溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot 2.X如何整合Spring-cache

發布時間:2021-09-08 11:30:44 來源:億速云 閱讀:198 作者:小新 欄目:編程語言

這篇文章將為大家詳細講解有關SpringBoot 2.X如何整合Spring-cache,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

一、Spring Cache介紹

Spring 3.1引入了基于注解的緩存(cache)技術,它本質上是一個對緩存使用的抽象,通過在既有代碼中添加少量它定義的各種注解,就能夠達到緩存方法的效果。

Spring Cache接口為緩存的組件規范定義,包含緩存的各種操作集合,并提供了各種xxxCache的實現,如RedisCache,EhCacheCache,ConcurrentMapCache等;

項目整合Spring Cache后每次調用需要緩存功能的方法時,Spring會檢查檢查指定參數的指定的目標方法是否已經被調用過,如果有就直接從緩存中獲取結果,沒有就調用方法并把結果放到緩存。

二、緩存注解介紹

對于緩存聲明,Spring的緩存提供了一組java注解:

@CacheConfig:設置類級別上共享的一些常見緩存設置。

  • @Cacheable:觸發緩存寫入。

  • @CacheEvict:觸發緩存清除。

  • @Caching 將多種緩存操作分組

  • @CachePut:更新緩存(不會影響到方法的運行)。

@CacheConfig

@CacheConfig(cacheNames = "user")
@Service
public class UserServiceImpl implements UserService {}

@Cacheable

  • 如果key不存在,查詢db,并將結果更新到緩存中。

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

  //查詢數據庫后 數據添加到緩存
  @Override
  @Cacheable(cacheNames = "cacheManager", key = "'USER:'+#id", unless = "#result == null")
  public User getUser(Integer id) {
    return repository.getUser(id);
  }

@CachePut

  //修改數據后更新緩存
  @Override
  @CachePut(cacheNames = "cacheManager", key = "'USER:'+#updateUser.id", unless = "#result == null")
  public User updateUser(User updateUser) {
    return repository.save(updateUser);
  }

@CacheEvict

  //清除一條緩存,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執行處理。

啟動類部分代碼如下:

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
# 連接池最大連接數(如果配置&lt;=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,增加緩存后速度提升非常明顯。

SpringBoot 2.X如何整合Spring-cache

postman訪問截圖

SpringBoot 2.X如何整合Spring-cache

日志截圖

7、注意事項

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

關于“SpringBoot 2.X如何整合Spring-cache”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女