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

com.scaffold.redis.RedisConfigurator Maven / Gradle / Ivy

The newest version!
package com.scaffold.redis;


import com.alibaba.fastjson2.support.spring6.data.redis.GenericFastJsonRedisSerializer;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
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.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;


/**
 * @描述 redis配置类 使用Lettuce客户端,手动注入配置的方式
 * @创建人 李亮
 * @创建时间 2022-08-03 10:18:32
 */
@Configuration
@EnableCaching
public class RedisConfigurator extends CachingConfigurerSupport {

    @Autowired
    private RedisConfigProperties redisConfigProperties;


    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(getConnectionFactory());
//        container.addMessageListener(getApiLogConsumer(), getApiLogTopic());
//        container.addMessageListener(getOperationLogConsumer(), getOperationLogTopic());
        return container;
    }
    /* 消息队列配置 */

    /**
     * 自定义缓存key的生成策略。默认的生成策略是看不懂的(乱码内容)
     * 通过Spring 的依赖注入特性进行自定义的配置注入并且此类是一个配置类可以更多程度的自定义配置
     *
     * @return
     */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

    /**
     * 缓存配置管理器 @Cacheable注解字符集编码配置
     */
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory factory) {
        //新版本在这里配置key和value 的序列化工具
        GenericFastJsonRedisSerializer fastJsonRedisSerializer = genericFastJsonRedisSerializer();
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer));
        return RedisCacheManager
                .builder(factory)
                .cacheDefaults(config)
                .build();
    }

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        GenericFastJsonRedisSerializer fastJsonRedisSerializer = genericFastJsonRedisSerializer();
        template.setDefaultSerializer(fastJsonRedisSerializer);
//
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
//        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
//        // value序列化方式采用jackson
        template.setValueSerializer(fastJsonRedisSerializer);
//        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(fastJsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(factory);
        template.afterPropertiesSet();
        return template;
    }

    public GenericFastJsonRedisSerializer genericFastJsonRedisSerializer() {
        //开启JSONB,降低可读性,提升序列化效率,减少空间占用
        return new GenericFastJsonRedisSerializer(true);
    }

    /**
     * @描述 弃用
     * @参数
     * @返回值: org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer
     * @异常
     * @创建人 李亮
     * @创建时间 2022-08-23 09:46:52
     */
//    @Deprecated
//    private Jackson2JsonRedisSerializer getJackson2JsonRedisSerializer() {
//        //此种序列化方式结果清晰、容易阅读、存储字节少、速度快,所以推荐更换
//        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
//        ObjectMapper om = new ObjectMapper();
//        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
//        //解决不能序列化java8中的时间对象问题
//        om.registerModule(new JavaTimeModule());
//        jackson2JsonRedisSerializer.setObjectMapper(om);
//        return jackson2JsonRedisSerializer;
//    }

    /**
     * 获取缓存连接
     *
     * @return
     */
    @Bean
    public RedisConnectionFactory getConnectionFactory() {
        //单机模式
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(redisConfigProperties.getHost());
        configuration.setPort(redisConfigProperties.getPort());
        configuration.setDatabase(redisConfigProperties.getDatabase());
        configuration.setPassword(RedisPassword.of(redisConfigProperties.getPassword()));
        //哨兵模式
        //RedisSentinelConfiguration configuration1 = new RedisSentinelConfiguration();
        //集群模式
        //RedisClusterConfiguration configuration2 = new RedisClusterConfiguration();
        LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration, getPoolConfig());
        //factory.setShareNativeConnection(false);//是否允许多个线程操作共用同一个缓存连接,默认true,false时每个操作都将开辟新的连接
        return factory;
    }

    /**
     * 获取缓存连接池
     *
     * @return
     */
    @Bean
    public LettucePoolingClientConfiguration getPoolConfig() {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(redisConfigProperties.getLettuce().getPool().getMaxActive());
        config.setMaxWait(Duration.ofMillis(redisConfigProperties.getLettuce().getPool().getMaxWait()));
        config.setMaxIdle(redisConfigProperties.getLettuce().getPool().getMaxIdle());
        config.setMinIdle(redisConfigProperties.getLettuce().getPool().getMinIdle());
        return LettucePoolingClientConfiguration.builder()
                .poolConfig(config)
                .commandTimeout(Duration.ofMillis(redisConfigProperties.getLettuce().getCommandTimeout()))
                .shutdownTimeout(Duration.ofMillis(redisConfigProperties.getLettuce().getShutdownTimeout()))
                .build();
    }

}