好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

@CacheEvict + redis实现批量删除缓存

@CacheEvict + redis批量删除缓存

一、@Cacheable注解

添加缓存。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

/**

  * @Cacheable

  * 将方法的运行结果进行缓存;以后再要相同的数据,直接从缓存中获取,不用调用方法;

  * CacheManager管理多个Cache组件,对缓存的真正CRUD操作在Cache组件中,每一个缓存组件有自己唯一一个名字;

  *

  *

  * 原理:

  *   1、自动配置类;CacheAutoConfiguration

  *   2、缓存的配置类

  *   org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration

  *   org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration

  *   org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration

  *   org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration

  *   org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration

  *   org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration

  *   org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration

  *   org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration

  *   org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration

  *   org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration【默认】

  *   org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration

  *   3、哪个配置类默认生效:SimpleCacheConfiguration;

  *

  *   4、给容器中注册了一个CacheManager:ConcurrentMapCacheManager

  *   5、可以获取和创建ConcurrentMapCache类型的缓存组件;他的作用将数据保存在ConcurrentMap中;

  *

  *   运行流程:

  *   @Cacheable:

  *   1、方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;

  *      (CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。

  *   2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;

  *      key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key;

  *          SimpleKeyGenerator生成key的默认策略;

  *                  如果没有参数;key=new SimpleKey();

  *                  如果有一个参数:key=参数的值

  *                  如果有多个参数:key=new SimpleKey(params);

  *   3、没有查到缓存就调用目标方法;

  *   4、将目标方法返回的结果,放进缓存中

  *

  *   @Cacheable标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,

  *   如果没有就运行方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;

  *

  *   核心:

  *      1)、使用CacheManager【ConcurrentMapCacheManager】按照名字得到Cache【ConcurrentMapCache】组件

  *      2)、key使用keyGenerator生成的,默认是SimpleKeyGenerator

  *

  *

  *   几个属性:

  *      cacheNames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存;

  *

  *      key:缓存数据使用的key;可以用它来指定。默认是使用方法参数的值  1-方法的返回值

  *              编写SpEL; #i d;参数id的值   #a0  #p0  #root.args[0]

  *              getEmp[2]

  *

  *      keyGenerator:key的生成器;可以自己指定key的生成器的组件id

  *              key/keyGenerator:二选一使用;

  *

  *

  *      cacheManager:指定缓存管理器;或者cacheResolver指定获取解析器

  *

  *      condition:指定符合条件的情况下才缓存;

  *              ,condition = "#id>0"

  *          condition = "#a0>1":第一个参数的值》1的时候才进行缓存

  *

  *      unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存;可以获取到结果进行判断

  *              unless = "#result == null"

  *              unless = "#a0==2":如果第一个参数的值是2,结果不缓存;

  *      sync:是否使用异步模式

  *

  */

二、@CacheEvict注解

清除缓存。

cacheNames/value: 指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存;
key 缓存数据使用的key
allEntries 是否清除这个缓存中所有的数据。true:是;false:不是
beforeInvocation 缓存的清除是否在方法之前执行,默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除。true:是;false:不是

三、批量删除缓存

现实应用中,某些缓存都有相同的前缀或者后缀,数据库更新时,需要删除某一类型(也就是相同前缀)的缓存。

而@CacheEvict只能单个删除key,不支持模糊匹配删除。

解决办法:使用redis + @CacheEvict解决。

@CacheEvict实际上是调用RedisCache的evict方法删除缓存的。下面为RedisCache的部分代码,可以看到,evict方法是不支持模糊匹配的,而clear方法是支持模糊匹配的。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

/*

  * (non-Javadoc)

  * @see org.springframework.cache.Cache#evict(java.lang.Object)

  */

@Override

public void evict(Object key) {

     cacheWriter.remove(name, createAndConvertCacheKey(key));

}

 

/*

  * (non-Javadoc)

  * @see org.springframework.cache.Cache#clear()

  */

@Override

public void clear() {

 

     byte [] pattern = conversionService.convert(createCacheKey( "*" ), byte []. class );

     cacheWriter.clean(name, pattern);

}

所以,只需重写RedisCache的evict方法就可以解决模糊匹配删除的问题。

四、代码

4.1 自定义RedisCache:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

public class CustomizedRedisCache extends RedisCache {

     private static final String WILD_CARD = "*" ;

     private final String name;

     private final RedisCacheWriter cacheWriter;

     private final ConversionService conversionService;

     protected CustomizedRedisCache(String name, RedisCacheWriter cacheWriter, RedisCacheConfiguration cacheConfig) {

         super (name, cacheWriter, cacheConfig);

         this .name = name;

         this .cacheWriter = cacheWriter;

         this .conversionService = cacheConfig.getConversionService();

     }

 

     @Override

     public void evict(Object key) {

         if (key instanceof String) {

             String keyString = key.toString();

             if (keyString.endsWith(WILD_CARD)) {

                 evictLikeSuffix(keyString);

                 return ;

             }

             if (keyString.startsWith(WILD_CARD)) {

                 evictLikePrefix(keyString);

                 return ;

             }

         }

         super .evict(key);

     }

 

     /**

      * 前缀匹配

      *

      * @param key

      */

     public void evictLikePrefix(String key) {

         byte [] pattern = this .conversionService.convert( this .createCacheKey(key), byte []. class );

         this .cacheWriter.clean( this .name, pattern);

     }

 

     /**

      * 后缀匹配

      *

      * @param key

      */

     public void evictLikeSuffix(String key) {

         byte [] pattern = this .conversionService.convert( this .createCacheKey(key), byte []. class );

         this .cacheWriter.clean( this .name, pattern);

     } 

}

4.2 重写RedisCacheManager,使用自定义的RedisCache:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

public class CustomizedRedisCacheManager extends RedisCacheManager {

     private final RedisCacheWriter cacheWriter;

     private final RedisCacheConfiguration defaultCacheConfig;

     private final Map<String, RedisCacheConfiguration> initialCaches = new LinkedHashMap<>();

     private boolean enableTransactions;

 

     public CustomizedRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {

         super (cacheWriter, defaultCacheConfiguration);

         this .cacheWriter = cacheWriter;

         this .defaultCacheConfig = defaultCacheConfiguration;

     }

 

     public CustomizedRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration, String... initialCacheNames) {

         super (cacheWriter, defaultCacheConfiguration, initialCacheNames);

         this .cacheWriter = cacheWriter;

         this .defaultCacheConfig = defaultCacheConfiguration;

     }

 

     public CustomizedRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration, boolean allowInFlightCacheCreation, String... initialCacheNames) {

         super (cacheWriter, defaultCacheConfiguration, allowInFlightCacheCreation, initialCacheNames);

         this .cacheWriter = cacheWriter;

         this .defaultCacheConfig = defaultCacheConfiguration;

     }

 

     public CustomizedRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration, Map<String, RedisCacheConfiguration> initialCacheConfigurations) {

         super (cacheWriter, defaultCacheConfiguration, initialCacheConfigurations);

         this .cacheWriter = cacheWriter;

         this .defaultCacheConfig = defaultCacheConfiguration;

     }

 

     public CustomizedRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration, Map<String, RedisCacheConfiguration> initialCacheConfigurations, boolean allowInFlightCacheCreation) {

         super (cacheWriter, defaultCacheConfiguration, initialCacheConfigurations, allowInFlightCacheCreation);

         this .cacheWriter = cacheWriter;

         this .defaultCacheConfig = defaultCacheConfiguration;

     }

 

     /**

      * 这个构造方法最重要

      **/

     public CustomizedRedisCacheManager(RedisConnectionFactory redisConnectionFactory, RedisCacheConfiguration cacheConfiguration) {

         this (RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),cacheConfiguration);

     }

 

     /**

      * 覆盖父类创建RedisCache

      */

     @Override

     protected RedisCache createRedisCache(String name, @Nullable RedisCacheConfiguration cacheConfig) {

         return new CustomizedRedisCache(name, cacheWriter, cacheConfig != null ? cacheConfig : defaultCacheConfig);

     }

 

     @Override

     public Map<String, RedisCacheConfiguration> getCacheConfigurations() {

         Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>(getCacheNames().size());

         getCacheNames().forEach(it -> {

             RedisCache cache = CustomizedRedisCache. class .cast(lookupCache(it));

             configurationMap.put(it, cache != null ? cache.getCacheConfiguration() : null );

         });

         return Collections.unmodifiableMap(configurationMap);

     }

}

4.3 在RedisTemplateConfig中使用自定义的CacheManager

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

@Bean

  public CacheManager oneDayCacheManager(RedisConnectionFactory factory) {

   RedisSerializer<String> redisSerializer = new StringRedisSerializer();

   Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object. class );

 

   //解决查询缓存转换异常的问题

   ObjectMapper om = new ObjectMapper();

   om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

   om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

   jackson2JsonRedisSerializer.setObjectMapper(om);

 

   // 配置序列化(解决乱码的问题)

   RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()

     // 1天缓存过期

     .entryTtl(Duration.ofDays( 1 ))

     .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))

     .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))

     测试数据putePrefixWith(name -> name + ":" )

     .disableCachingNullValues();

   return new CustomizedRedisCacheManager(factory, config);

  }

4.4 在代码方法上使用@CacheEvict模糊匹配删除

?

1

2

3

4

5

6

7

8

9

@Cacheable (value = "current_group" , cacheManager = "oneDayCacheManager" ,

             key = "#currentAttendanceGroup.getId() + ':' + args[1]" , unless = "#result eq null" )

     public String getCacheAttendanceId(CurrentAttendanceGroupDO currentAttendanceGroup, String dateStr) {

         // 方法体

     }

 

     @CacheEvict (value = "current_group" , key = "#currentAttendanceGroup.getId() + ':' + '*'" , beforeInvocation = true )

     public void deleteCacheAttendanceId(CurrentAttendanceGroupDO currentAttendanceGroup) {

     }

注意:如果RedisTemplateConfig中有多个CacheManager,可以使用@Primary注解标注默认生效的CacheManager

@CacheEvict清除指定下所有缓存

?

1

@CacheEvict (cacheNames = "parts:grid" ,allEntries = true )

此注解会清除part:grid下所有缓存

@CacheEvict要求指定一个或多个缓存,使之都受影响。

此外,还提供了一个额外的参数allEntries 。表示是否需要清除缓存中的所有元素。

默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。

有的时候我们需要Cache一下清除所有的元素。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/llllllllll4er5ty/article/details/106337559

查看更多关于@CacheEvict + redis实现批量删除缓存的详细内容...

  阅读:74次