Springboot緩存與redis整合

Springboot緩存
  1. Spring緩存抽象
    1. 重要概念以及緩存註解
      1. Cache:緩存接口,定義緩存操作,實現又:RedisCache,EhCacheCache,ConcurrentMapCache等
      2. CacheManager:緩存管理器,管理各種緩存組件
      3. @Cacheable:修飾方法,能夠根據方法的請求參數和返回結果進行緩存
      4. @CacheEvict:修飾方法,清空緩存,例如從數據庫刪除某個用戶,那就需要把相應的緩存也刪除掉
      5. @CachePut:修飾方法,調用函數,更新緩存
        1. @Cacheable一旦緩存命中,就不再調用修飾的函數了
        2. @CachePut一定會調用函數,並把值放到緩存,常用於更新操作,先調用函數,在更新緩存
      6. @EnableCaching:開啓基於註解的緩存模式
      7. keyGenerator:緩存數據時key的生成策略
      8. serialize:緩存數據時value序列化策略
    2. 搭建環境
      1. 引入包
        1. <dependency>
        2. <groupId>org.springframework.boot</groupId>
        3. <artifactId>spring-boot-starter-cache</artifactId>
        4. </dependency>
      2. 使用緩存
        @Cacheable
        public String getUser(int id){
        System.out.println("緩存未命中");
        return "zhangsan";
        }
        1. 開啓基於註解的緩存
          1.  
             
        2. 使用緩存
    3. @Cacheable
      @Caching(
      cacheable={@Cacheable(),@Cacheable()},
      put={},
      evict = {}
      )
      1. 屬性
        1. cacheNames/value:數組,緩存名字,因爲緩存管理器下有許多緩存,所以這個指定從哪個緩存中查找數據,或者將數據存入哪個緩存中,可以將一份數據存到多個緩存
          1. @Cacheable(cacheNames="emp")
        2. key:存緩存或者查找緩存value時用的鍵,支持spel表達式。默認key爲參數的值
          1. @Cacheable的key不能用#result
        3. keyGenerator:key的生成器,可以指定key生成器的組件id,key和keyGenerator兩個屬性二選一
          @Configuration
          public class CacheAutoConfiguration{
          @Bean("myKeyGenerator")
          public KeyGenerator keyGenerator(){
          return new KeyGenerator() {
          @Override
          public Object generate(Object target, Method method, Object... params) {
          return "hahaha";
          }
          }
          }
          }
          1. 自定義keyGenerator
          2. 使用自定義的keyGenerator
            1. @Cacheable(cacheNames = "emp", keyGenerator = "myKeyGenerator")
        4. cacheManager:指定從哪個緩存管理器中拿到緩存,
        5. cacheResolver:指定尋找 cacheManager的策略,cacheResolver與cacheManager二選一
        6. condition:可以使用spel表達式,滿足條件才緩存
        7. unless:滿足unless條件,則不緩存,可以獲取到結果進行判斷
          1. @Cacheable(unless="#result == null")
        8. sync:是否使用異步模式,默認false.意思是。在put數據時,是異步還是同步
      2. 原理
        1. 自動配置類:CacheAutoConfiguration
        2. Import選擇器:CacheConfigurationImportSelector
          1. org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
          2. org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
          3. org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
          4. org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
          5. org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
          6. org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
          7. org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
          8. org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
          9. org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration
          10. org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
        3. 哪個配置生效呢?
          1. 每個CacheConfiguration上面都用註解標識了生效條件
          2. SimpleCacheConfiguration這個有可能生效
        4. SimpleCacheConfiguration給容器中注入了一個CacheManager(ConcurrentMapCacheManager)的bean
          1. ConcurrentMapCacheManager維護了一個Map<String,ConcurrentMapCache>,String爲緩存的名字
        5. ConcurrentMapCacheManager可以獲取和創建ConcurrentMapCache組件,並將數據放到ConcurrentMapCache中
          1. ConcurrentMapCache就是一個類,屬性有name和ConcurrentMap
        6. 整個流程
      3. @CachePut
        1. 先調用函數在更新緩存
        2. 注意點
          1. @Cacheable添加緩存
            1. @Cacheable(cacheNames = "emp", keyGenerator = "myKeyGenerator")
            2. public String getUser(int id){
          2. @CachePut添加緩存
            1. @CachePut(cacheNames = "emp")
            2. public Employee update(Employee emp){
          3. 這兩個緩存的key的生成可能不一楊,可能會導致他們更新的緩存原本應該是同一個,但是卻由於生成key不一樣,導致緩存更新錯誤
      4. @CacheEvict
        1. key:指定要清除的key
        2. allEntries=true:清除緩存中的所有數據,默認false
        3. beforeInvocation=true:實在方法執行之前清除緩存,還是在方法執行之後清除緩存,默認爲false,
          1. 如果在方法執行之後清除緩存,一旦方法出現異常,那麼緩存不會被清除
      5. @Caching可以使用組合註解
      6. @CacheConfig修飾類,可以將Cacheable,CachePut,CacheEvict的公共屬性提取出來
  2. 整合redis使用緩存
     
    1. 引入依賴
      1. <!-- springboot整合redis的starter-->
      2. <dependency>
      3. <groupId>org.springframework.boot</groupId>
      4. <artifactId>spring-boot-starter-data-redis</artifactId>
      5. </dependency>
      6. <!-- redis如果要使用連接池技術,需要依賴這個包-->
      7. <dependency>
      8. <groupId>org.apache.commons</groupId>
      9. <artifactId>commons-pool2</artifactId>
      10. </dependency>
      11. <!-- 由於我們需要更改對象序列化爲json存到redis中,需要這個包-->
      12. <dependency>
      13. <groupId>com.fasterxml.jackson.core</groupId>
      14. <artifactId>jackson-core</artifactId>
      15. <version>2.9.8</version>
      16. </dependency>
      17. <!-- 從redis讀取數據,反序列化爲對象時,綁定數據需要這個包 -->
      18. <dependency>
      19. <groupId>com.fasterxml.jackson.core</groupId>
      20. <artifactId>jackson-databind</artifactId>
      21. <version>2.9.8</version>
      22. </dependency>
    2. 配置redis連接池
      1. spring:
        1. redis:
          1. host: 127.0.0.1
          2. port: 6379
          3. database: 0
          4. lettuce:
            1. pool:
              1. # 連接池最大連接數 默認8 ,負數表示沒有限制
              2. max-active: 20
              3. # 連接池中的最大空閒連接 默認8
              4. max-idle: 10
              5. # 連接池最大阻塞等待時間(使用負值表示沒有限制) 默認-1
              6. max-wait: 1000
          5. timeout: 10000
    3. 修改cacheManager的默認配置
    4. public CacheManager cacheManager(LettuceConnectionFactory redisConnectionFactory) {
      //初始化一個RedisCacheWriter
      RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
      //設置CacheManager的值序列化方式爲json序列化
      Jackson2JsonRedisSerializer<Person> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Person.class);
      RedisSerializationContext.SerializationPair<Person> pair = RedisSerializationContext.SerializationPair
      .fromSerializer(jackson2JsonRedisSerializer);
      RedisCacheConfiguration defaultCacheConfig= RedisCacheConfiguration.defaultCacheConfig()
      .serializeValuesWith(pair)
      .entryTtl(Duration.ofSeconds(30))//設置默認超過期時間是30
      .disableCachingNullValues();
       
      //初始化RedisCacheManager
      return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
      }
    5. 使用註解即可
      1. 開啓緩存@EnableCaching
      2. 在相應方法上添加註解
        1. @Cacheable(cacheNames = "statuschecker")
        2. public Person request(int id){
          1. System.out.println("Cache未命中");
          2. return new Person("www",24);
        3. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章