配置spring cache RedisCacheManager的序列化方法


通過查看autoconfigure源碼

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

部分源碼如下:

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 就直接使用了。

那么只需要自己注入一個 RedisCacheConfiguration 即可。

代碼可以直接用源碼里面的:),調整序列化部分即可。

 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 ;

參考文檔:

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

可以看到已有的可用序列化器:

GenericJackson2JsonRedisSerializerGenericToStringSerializerJackson2JsonRedisSerializerJdkSerializationRedisSerializerOxmSerializerStringRedisSerializer

這里順便學習一下 @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; } }

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM