SpringCache缓存处理

  1. 先导入springCache的缓存依赖  除了缓存的依赖和redis的依赖,下面的其他依赖可加可不加
  2.  1 <!--SpringCache配置-->
     2         <dependency>
     3             <groupId>org.springframework.boot</groupId>
     4             <artifactId>spring-boot-starter-cache</artifactId>
     5         </dependency>
     6         <!-- 因为lettuce导致堆外内存溢出 这里暂时排除他 使用jedis -->
     7         <dependency>
     8             <groupId>org.springframework.boot</groupId>
     9             <artifactId>spring-boot-starter-data-redis</artifactId>
    10             <exclusions>
    11                 <exclusion>
    12                     <groupId>io.lettuce</groupId>
    13                     <artifactId>lettuce-core</artifactId>
    14                 </exclusion>
    15             </exclusions>
    16         </dependency>
    17 
    18         <dependency>
    19             <groupId>redis.clients</groupId>
    20             <artifactId>jedis</artifactId>
    21         </dependency>
    22         <!--使用redissonzuowei suo-->
    23         <dependency>
    24             <groupId>org.redisson</groupId>
    25             <artifactId>redisson</artifactId>
    26             <version>3.12.0</version>
    27         </dependency>
  3. 首先在启动的主类里面开启缓存注解  @EnableCaching

  4. 手写一个缓存的配置类,主要是修改存储的key,value的数据序列化
  5.  1 package com.atguigu.gulimall.product.config;
     2 
     3 import org.springframework.boot.autoconfigure.cache.CacheProperties;
     4 import org.springframework.cache.annotation.Cacheable;
     5 import org.springframework.cache.annotation.EnableCaching;
     6 import org.springframework.context.annotation.Bean;
     7 import org.springframework.context.annotation.Configuration;
     8 import org.springframework.data.redis.cache.RedisCacheConfiguration;
     9 import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    10 import org.springframework.data.redis.serializer.RedisSerializationContext;
    11 import org.springframework.data.redis.serializer.StringRedisSerializer;
    12 
    13 /**
    14  * @Author: LiuLi
    15  * @Description:
    16  * @Date: Create in 11:21 2020/7/29
    17  */
    18 @Configuration
    19 @EnableCaching
    20 public class MyCacheConfig {
    21 
    22     @Bean
    23     RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
    24         RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
    25 
    26         config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
    27         config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
    28 
    29         CacheProperties.Redis redisProperties = cacheProperties.getRedis();
    30         if (redisProperties.getTimeToLive() != null) {
    31             config = config.entryTtl(redisProperties.getTimeToLive());
    32         }
    33         if (redisProperties.getKeyPrefix() != null) {
    34             config = config.prefixKeysWith(redisProperties.getKeyPrefix());
    35         }
    36         if (!redisProperties.isCacheNullValues()) {
    37             config = config.disableCachingNullValues();
    38         }
    39         if (!redisProperties.isUseKeyPrefix()) {
    40             config = config.disableKeyPrefix();
    41         }
    42 
    43         return config;
    44     }
    45 }
  6. 在yml或者properties中进行配置
  7. #在yml中redis的配置
    spring:
      redis:
        host: 192.168.56.10
        port: 6379
    
    
    #在properties中的springCache的配置
    # 使用redis进行缓存
    spring.cache.type=redis
    #设置缓存的存活时间(1h)
    spring.cache.redis.time-to-live=3600000
    # 配置缓存名的前缀 如果没配置则使用缓存名作为前缀
    #spring.cache.redis.key-prefix=CACHE_
    # 配置前缀是否生效  默认为ture
    #spring.cache.redis.use-key-prefix=false
    # 是否缓存空值 默认为true
    spring.cache.redis.cache-null-values=true
  8. 对@Cacheable() ,@CacheEvict(),@CachePut()和@Caching()进行运用
  9.  @Cacheable(value = {"category"}, key = "#root.methodName")首先存储缓存
    1. value:是缓存的分区名称   key:是将方法名当做缓存key ,缓存的值则是方法的返回数据
  10. @CachePut()  则是双写模式,它是可以注解在修改,删除或是添加的方法上面,前提是方法得有返回的数据  
  11. @CacheEvict(value = "category", allEntries = true)  // 失效模式 
    1. 这个模式是注解在方法上,然后再进行删除,修改或是添加的时候将缓存进行分区的清理,其中category就是缓存存储的一个区   
  12. @Caching(evict = {   @CacheEvict(value = "category", key = "'getLevelCategorys'"),   @CacheEvict(value = "category", key = "'getCatalogJson'")    })
    1. 同时进行多种缓存操作,这里是进行修改操作时删除缓存,可以一个或者多个区的缓存数据
  13.  具体的使用如下代码 :

   

 1     /**
 2      * 级联更新所有关联数据
 3      *
 4      * @param * @param category
 5      * @return void
 6      *
 7      * @CacheEvict(value="",key="''") 失效模式
 8      * @Caching(evict = {@CacheEvict,@CacheEvict}) 同时进行多种缓存操作,这里是进行修改操作时删除缓存
 9      * @CacheEvict(value = "category", allEntries = true) // 进行分区的缓存清除
10      *
11      */
12 //    @Caching(evict = {
13 //            @CacheEvict(value = "category", key = "'getLevelCategorys'"),
14 //            @CacheEvict(value = "category", key = "'getCatalogJson'")
15 //    })  这里的@Caching()和@CacheEvict()前者是可以进行多种缓存操作,后者是进行缓存的区域清理,所以注释了前者
16 @CacheEvict(value = "category", allEntries = true) // 进行分区的缓存清除 17 @Transactional 18 @Override 19 public void updateCascade(CategoryEntity category) { 20 this.updateById(category); 21 categoryBrandRelationService.updateCategory(category.getCatId(), category.getName()); 22 } 23 24 // 每个需要缓存的数据我们指定来方法那个名字的缓存,【缓存的分区,按照业务类型进行分】 25 @Cacheable(value = {"category"}, key = "#root.methodName") // 代表需要对当前的方法结果进行缓存,如果缓存中有,那么就不进行缓存,如果没有则进入方法进行结果的缓存 26 @Override 27 public List<CategoryEntity> getLevelCategorys() { 28 long l = System.currentTimeMillis(); 29 List<CategoryEntity> ctegoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0)); 30 System.out.println("消耗时间:" + (System.currentTimeMillis() - l)); 31 return ctegoryEntityList; 32 }

 

             

@CacheEvict(value = "category", key = "'getLevelCategorys'"),

猜你喜欢

转载自www.cnblogs.com/liuli-warriors/p/13397303.html