All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.bootfastconfig.cache.redis.RedisConfig Maven / Gradle / Ivy

package com.github.bootfastconfig.cache.redis;

import com.github.bootfastconfig.cache.AnnotationConfigCacheBuilder;
import com.github.bootfastconfig.cache.CacheBeanNameConstant;
import com.github.bootfastconfig.cache.CacheBuilder;
import com.github.bootfastconfig.cache.CacheSimpleConfig;
import com.github.bootfastconfig.springtool.SpringBeanUtil;
import com.github.bootfastconfig.springtool.StringUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * The type Redis config.
 */
@Configuration
@ConditionalOnClass(value = {
        RedisSerializer.class,
        RedisCacheConfiguration.class,
        RedisTemplate.class})
@ConditionalOnBean({RedisConnectionFactory.class})
public class RedisConfig implements InitializingBean {

    @Autowired(required = false)
    private RedisSerializer redisSerializer;


    @Autowired(required = false)
    private RedisCacheConfiguration redisCacheConfiguration;

    @Autowired(required = false)
    private List cacheConfigs;

    @Autowired
    private SpringBeanUtil springBeanUtil;

    @Autowired(required = false)
    private AnnotationConfigCacheBuilder annotationConfigCacheBuilder;


    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.redisCacheConfiguration == null) {
            this.redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        }
        if (this.redisSerializer != null) {
            this.redisCacheConfiguration = redisCacheConfiguration();
        }
    }


    /**
     * Cache manager cache manager.
     *
     * @param connectionFactory the connection factory
     * @return the cache manager
     */
    @Bean(CacheBeanNameConstant.REDIS_CACHE_MANAGER)
    @ConditionalOnMissingBean(name = {CacheBeanNameConstant.REDIS_CACHE_MANAGER})
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfig redisCacheConfig = initRedisCacheConfig();
        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.builder(new MyRedisCacheWriter(connectionFactory));
        Collection> cacheBuilder = redisCacheConfig.getCacheBuilder();
        if (!cacheBuilder.isEmpty()) {
            Map collect = cacheBuilder.stream().collect(Collectors.toMap(CacheBuilder::getName, CacheBuilder::get));
            builder.initialCacheNames(collect.keySet());
            builder.withInitialCacheConfigurations(collect);
        }
        builder.cacheDefaults(redisCacheConfig.getDefaultCache());
        return builder.build();
    }


    public RedisCacheConfiguration redisCacheConfiguration() {
        //设置CacheManager的值序列化方式为 fastJsonRedisSerializer,但其实RedisCacheConfiguration默认使用StringRedisSerializer序列化key,
        RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer);
        this.redisCacheConfiguration = this.redisCacheConfiguration.entryTtl(this.redisCacheConfiguration.getTtl())
                .serializeValuesWith(pair)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        return this.redisCacheConfiguration;
    }


    Function> getConversionFactory() {
        return new Function>() {
            @Override
            public CacheBuilder apply(CacheSimpleConfig cacheSimpleConfig) {
                if (cacheSimpleConfig.cacheName() == null || StringUtil.EMPTY.equals(cacheSimpleConfig.cacheName())) {
                    return null;
                }
                return RedisBuilder.builder().defaultCacheConfig(redisCacheConfiguration)
                        .name(cacheSimpleConfig.cacheName())
                        .expireAfterAccess(new com.github.bootfastconfig.cache.Duration(cacheSimpleConfig.duration(), cacheSimpleConfig.unit()))
                        .build();

            }
        };
    }

    RedisCacheConfig initRedisCacheConfig() {
        RedisCacheConfig redisCacheConfig = new RedisCacheConfig();
        if (annotationConfigCacheBuilder != null) {
            AnnotationConfigCacheBuilder annotationConfigCacheBuilder = this.annotationConfigCacheBuilder.setConversionFactory(getConversionFactory());
            redisCacheConfig.addCaches(annotationConfigCacheBuilder.get());
        }
        if (cacheConfigs != null) {
            for (RedisCacheConfigGather cacheConfig : cacheConfigs) {
                redisCacheConfig.addDefaultCache(cacheConfig.getDefaultRedisCacheConfig());
                cacheConfig.addRedisCacheConfig(redisCacheConfig);
            }
        }
        redisCacheConfig.addDefaultCache(redisCacheConfiguration);
        return redisCacheConfig;
    }


    @Bean("redisTemplate")
    public RedisTemplate redisTemplate(
            RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        if (redisSerializer != null) {
            // 值采用json序列化
            template.setValueSerializer(redisSerializer);
            //使用StringRedisSerializer来序列化和反序列化redis的key值
            template.setKeySerializer(new StringRedisSerializer());
            // 设置hash key 和value序列化模式
            template.setHashKeySerializer(new StringRedisSerializer());
            template.setHashValueSerializer(redisSerializer);
            template.afterPropertiesSet();
        }
        return template;
    }


}