配置spring cache RedisCacheManager的序列化方法

經過查看autoconfigure源碼html

org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration;

部分源碼以下:redis

private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration(
ClassLoader classLoader) {
if (this.redisCacheConfiguration != null) {
return this.redisCacheConfiguration;
}
Redis redisProperties = this.cacheProperties.getRedis();
org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
.defaultCacheConfig();
config = config.serializeValuesWith(SerializationPair
.fromSerializer(new JdkSerializationRedisSerializer(classLoader)));
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;
}

能夠看到默認是使用的 JdkSerializationRedisSerializer ,還有就是若是容器裏已經有 redisCacheConfiguration 就直接使用了。spring

那麼只須要本身注入一個 RedisCacheConfiguration 便可。api

代碼能夠直接用源碼裏面的:),調整序列化部分便可。緩存

 1 @Configuration
 2 @Conditional(SimpleCacheCondition.class)
 3 public class MyRedisCacheConfiguration {
 4     private final CacheProperties cacheProperties;
 5     MyRedisCacheConfiguration(CacheProperties cacheProperties) {
 6         this.cacheProperties = cacheProperties;
 7     }
 8     @Bean
 9     public org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration() {
10         CacheProperties.Redis redisProperties = this.cacheProperties.getRedis();
11         org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
12                 .defaultCacheConfig();
13         config = config.serializeValuesWith(RedisSerializationContext.SerializationPair
14                 .fromSerializer(valueSerializer()));
15         if (redisProperties.getTimeToLive() != null) {
16             config = config.entryTtl(redisProperties.getTimeToLive());
17         }
18         if (redisProperties.getKeyPrefix() != null) {
19             config = config.prefixKeysWith(redisProperties.getKeyPrefix());
20         }
21         if (!redisProperties.isCacheNullValues()) {
22             config = config.disableCachingNullValues();
23         }
24         if (!redisProperties.isUseKeyPrefix()) {
25             config = config.disableKeyPrefix();
26         }
27         return config;
28     }
29     /**
30      * 使用Jackson序列化器
31      * @return
32      */
33     private RedisSerializer<Object> valueSerializer() {
34         ObjectMapper objectMapper = new ObjectMapper();
35         objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
36         objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
37         return new GenericJackson2JsonRedisSerializer(objectMapper);
38     }
39 
40 }

這裏使用的是 GenericJackson2JsonRedisSerializer ;app

參考文檔:ide

https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/serializer/RedisSerializer.html學習

能夠看到已有的可用序列化器:this

GenericJackson2JsonRedisSerializerGenericToStringSerializerJackson2JsonRedisSerializerJdkSerializationRedisSerializerOxmSerializerStringRedisSerializerspa

這裏順便學習一下 @Conditional ,這個註解能夠幫咱們控制何時來註冊組件。

好比這裏寫了一個 RedisCacheConfiguration 配置,那我只想在啓用了redis緩存時再註冊,就能夠使用這個註解,如 @Conditional(SimpleCacheCondition.class) 。

定義 SimpleCacheCondition ,部分代碼參考 org.springframework.boot.autoconfigure.cache.CacheCondition 

public class SimpleCacheCondition implements Condition {

    /**
     * Determine if the condition matches.
     *
     * @param context  the condition context
     * @param metadata metadata of the {@link AnnotationMetadata class}
     *                 or {@link MethodMetadata method} being checked
     * @return {@code true} if the condition matches and the component can be registered,
     * or {@code false} to veto the annotated component's registration
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        try {
            String sourceClass = "";
            if (metadata instanceof ClassMetadata) {
                sourceClass = ((ClassMetadata) metadata).getClassName();
            }
            Environment environment = context.getEnvironment();
            BindResult<CacheType> specified = Binder.get(environment)
                    .bind("spring.cache.type", CacheType.class);
            if (!specified.isBound()) {
                return false;
            }
       //redis cache 啓用 而且 是自定義的redisCacheConfiguration
if (specified.get().equals(CacheType.REDIS) && sourceClass.equals(MyRedisCacheConfiguration.class.getTypeName())) { return true; } }catch (Exception ex) {} return false; } }
相關文章
相關標籤/搜索