SpringBoot——Cache使用原理及Redis整合

前言及核心概念介紹

前言java

本篇主要介紹SpringBoot2.x 中 Cahe 的原理及幾個主要註解,以及整合 Redis 做爲緩存的步驟redis

核心概念spring

先來看看核心接口的做用及關係圖:docker

CachingProvider  管理並建立CacheManager,一個CachingProvider能夠管理多個CacheManager數據庫

CacheManager  管理並建立Cache,一個CacheManager管理多個Cache  數組

Cache  結構相似於Map<CacheName,Cache>,每一個Cache有惟一的名字緩存

Entry 結構相似於Map<KeyObject,ValueObject>,以鍵值對的形式儲存在Cache中springboot

Expiry  Cache中每一個條目都有有效期,過時則會被刪除或更新ide

 


 

 

1、SpringBoot中的緩存結構:

要知道SpringBoot是經過XXXAutoConfiguration來向容器中註冊組件的spring-boot

因此只要知道CacheAutoConfiguration註冊了哪些組件,咱們就能入手進行分析

找到添加的組件

一、首先進入CacheAutoConfiguration
  
能夠看到其導入了CacheConfigurationImportSelector
  從名字能夠看出它是用來導入緩存配置類的

 

二、進入CacheConfigurationImportSelector
  這是一個靜態內部類,只有一個selectImports方法,方法的最後將字符串數組返回
  咱們在方法上打上斷點進行測試



三、執行完第二步的方法,直接查看最終的返回結果
  能夠看到返回了不少XXXCacheConfiguration



四、在配置文件中添加 debug=true
  要想知道到底用了哪一個CacheConfiguration,咱們能夠在配置文件中添加 debug=true 來查看詳細的日誌
  啓動應用,在日誌中搜索CacheConfiguration,會發現只有SimpleCacheConfiguration是matched
  而其餘的XXXCacheConfiguration都是Did not match
  結論:springboot默認使用SimpleCacheConfiguration做爲緩存配置類  
找到了配置類,順着配置類一層層進入,就能很快了解其中的結構


查看緩存結構
  一、進入默認配置類SimpleCacheConfiguration
  發現配置類中註冊了ConcurrentMapCacheManager做爲CacheManager
  注意:@ConditionalOnMissingBean(CacheManager.class)註解
當容器中存在CacheManager時,本配置類就不會生效,而CacheManager是經過配置類建立的,也就是說,若是選擇了
其餘的XXXCacheConfiguration,就會生成其餘的CacheManager,本配置類就不會起做用。
這也是咱們後面導入Redis的startor後就會自動使用RedisCacheConfiguration的緣由

   

二、進入ConcurrentMapCacheManager
  cacheMap正是ConcurrentMapCacheManager管理的Cache結構



三、經過調試,找到這裏的Cache實現類爲ConcurrentMapCache
  其中兩個屬性,name爲cache的名字,store用於儲存鍵值對


到此爲止,springboot的默認cache結構就出來了,接下來看看咱們實現緩存功能須要的經常使用註解以及他們要注意的地方

 

 

2、幾個關鍵註解

  一、@Cacheable

    標註在方法上,將方法返回的結果存入緩存中

    能夠指定cachename或value來對ConcurrentMapCache的name屬性進行設置

    也能夠經過指定keyGenerator來制定緩存鍵值對中生成key的規則 

    默認狀況:name爲傳入的參數,鍵值對中的值爲方法返回結果 

   二、@CachePut

    標註在方法上,先執行方法,再用方法返回的值來更新緩存內容

   三、@CacheEvict

    清除緩存

   四、@Caching

    複雜的cache配置,能夠在裏面配置上面的幾個註解

   五、@CacheConfig

    標註在類上,對類中的緩存操做做統一配置

 

 

3、@Cacheable工做原理

  下來經過幾個重要的方法來展現@Cacheable工做原理

  這裏的測試方法將從數據庫中獲取1號員工的數據,方法上只標註了@Cacheable

 

第一次查詢

一、第一個重要方法:ConcurrentMapCacheManager.getCache(String name) 方法具體以下圖

 在ConcurrentMapCacheManager中,查看cacheMap中是否存在名爲emp的Cache

 若是存在則返回這個cache,若是不存在,就以傳入的name做爲cache的name建立並返回

 這裏咱們是不存在的,因此建立並返回一個名爲emp的cache

 

二、因爲是第一次查詢,緩存中確定是不存在任何員工的內容的,

因此接下來仍是會執行真正的查詢方法,調用數據庫操做

 

三、返回結果以後,調用前面建立的cache,並調用其put方法,把員工id,員工信息,以鍵值對的方式存入cache中

 

 

第二次查詢

有了上面的查詢,1號員工的信息已經被緩存起來了

接下來看看再次查詢1號員工會發生什麼

 

一、首先仍是進入 ConcurrentMapCacheManager 的 getCache 方法查找 cache

  由於第一次的操做,cacheMap中存在名爲emp的cache,因此直接返回cache

 

二、接下來調用cache的lookup方法,經過鍵查找值

 

 

 三、再接着方法將查找到的值返回,而後就直接結束了,沒有調用實際的數據庫操做

 

總結

在第一次查詢時,會建立cache,而後調用方法,最後將方法的返回值存入cache

這樣在查找相同內容時就直接從cache中獲取,無需調用方法操做數據庫來查找

 

 

4、整合Redis

一、加入redis的startor,springboot會自動識別並使用RedisCacheConfiguration,具體緣由上面有提到

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

二、開啓Redis服務(可使用docker)

三、建立配置類,配置RedisCacheManager(配置序列號方式等屬性)

package com.tlj.cache.config;

import com.tlj.cache.bean.Department;
import com.tlj.cache.bean.Employee;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

@Configuration
public class RedisConfig {

//    @Bean
//    public RedisTemplate<Object, Employee> empRedisTemplate(
//            RedisConnectionFactory redisConnectionFactory){
//        RedisTemplate<Object,Employee> template=new RedisTemplate<Object,Employee>();
//        template.setConnectionFactory(redisConnectionFactory);
//        Jackson2JsonRedisSerializer<Employee> redisSerializer=new Jackson2JsonRedisSerializer<Employee>(Employee.class);
//        template.setDefaultSerializer(redisSerializer);
//        return template;
//    }

//    @Bean
//    public RedisCacheConfiguration redisCacheConfiguration(){
//        Jackson2JsonRedisSerializer<Employee> Jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
//        RedisSerializationContext.SerializationPair<Employee> pair = RedisSerializationContext.SerializationPair.fromSerializer(Jackson2JsonRedisSerializer);
//        return RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
//    }

    /**
     * 或者直接跳過RedisCacheConfiguration建立RedisCacheManager
     * (在多個manager的狀況下能夠在@CacheConfig指定)
     * @param redisConnectionFactory
     * @return
     */
    @Primary//多個Manager時須要設置
    @Bean
    public RedisCacheManager empCacheManager(RedisConnectionFactory redisConnectionFactory){
        //初始化一個RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        //設置CacheManager的值序列化方式爲Jackson2JsonRedisSerializer
        Jackson2JsonRedisSerializer<Employee> Jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        RedisSerializationContext.SerializationPair<Employee> pair = RedisSerializationContext.SerializationPair.fromSerializer(Jackson2JsonRedisSerializer);
        RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
        //設置默認超過時時間是30秒
        defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
        //初始化RedisCacheManager
        RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
        return cacheManager;
    }

    @Bean
    public RedisCacheManager deptCacheManager(RedisConnectionFactory redisConnectionFactory){
        //初始化一個RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        //設置CacheManager的值序列化方式爲Jackson2JsonRedisSerializer
        Jackson2JsonRedisSerializer<Department> Jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Department>(Department.class);
        RedisSerializationContext.SerializationPair<Department> pair = RedisSerializationContext.SerializationPair.fromSerializer(Jackson2JsonRedisSerializer);
        RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
        //設置默認超過時時間是30秒
        defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
        //初始化RedisCacheManager
        RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
        return cacheManager;
    }
}
RedisConfig

 四、在對應的類上指定對應的RedisCacheManager,相似下圖

相關文章
相關標籤/搜索