①cache配置过程
1、找到CacheAutoConfiguration类
内部有个配置类加载选择器,决定了哪个配置类会被加载!
2、找到CacheConfigurations类
RedisCacheConfiguration为redis的缓存配置类。
3、找到RedisCacheConfiguration类
RedisCacheConfiguration向spring中放入了RedisCacheManager的bean,用于管理Redis的Cache。
其中有个方法:determineConfiguration()决定哪个redis缓存配置类生效。
4、转到determineConfiguration()方法
5、cache配置真相
-
ObjectProvider表示是从spring的容器中取值;网址:ObjectProvider使用说明 - 枫雪奕 - 博客园
-
determineConfiguration()方法表示在spring容器中如果自己配置了RedisCacheConfiguration类,则取得并使用该类;
-
如果没有配置,则使用默认的RedisCacheConfiguration类!
6、找到RedisCacheConfiguration类
这个类中制定了序列化的方式!因此,我们只需要将其改造成自己的MyRedisCacheConfiguration 配置类,将其放入容器中即可!
7、找到CacheProperties类
这不就是在properties文件中配置的属性!
②自定义RedisCacheConfiguration配置类指定序列化方式!
package com.wang.test.config.cache;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author wang
* @date 2021/12/21 17:11
* @description: RedisCacheConfiguration
* @since 8
*/
@EnableConfigurationProperties(value = CacheProperties.class)//允许将配置属性配置类放入spring容器中
@Configuration
public class MyRedisCacheConfiguration {
/**
* 这里我们借鉴使用ObjectProvider,其实可以直接使用CacheProperties cacheProperties;
* 因为@EnableConfigurationProperties(value = CacheProperties.class),容器中放入了CacheProperties的Bean实例
* @param cacheProperties
* @return
*/
@Bean
public RedisCacheConfiguration redisCacheConfiguration(ObjectProvider<CacheProperties> cacheProperties){
//在默认配置上修改,也可以new一个。指定序列化方式!
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().
serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).
serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
//从容器中取得redisProperties并进行判断,不然在application.yml配置的文件无效。
// 因为只有默认的RedisCacheConfiguration才会走下面的内容,自定义的需要cv大法后改造一下
CacheProperties ifAvailable = cacheProperties.getIfAvailable();
if (null != ifAvailable){
CacheProperties.Redis redisProperties = ifAvailable.getRedis();
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixKeysWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
}
return config;
}
}