【问题标题】:How to create a second RedisTemplate instance in a Spring Boot application如何在 Spring Boot 应用程序中创建第二个 RedisTemplate 实例
【发布时间】:2016-06-01 17:45:22
【问题描述】:

根据this answer,一个RedisTemplate 不能支持多个序列化器的值。所以我想为不同的需求创建多个 RedisTemplates,特别是一个用于字符串操作和一个用于 JSON 序列化的对象,用于RedisCacheManager。我正在使用 Spring Boot 并且当前的 RedisTemplate 是自动装配的,我想知道声明第二个 RedisTemplate 实例共享同一个 Jedis 连接工厂但有自己的序列化程序的正确方法是什么?

在两个不同的组件中尝试过类似的东西,

组件 1 声明,

    @Autowired
    private RedisTemplate redisTemplate;

    redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Instance.class));

组件 2 声明,

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

在这种情况下,这两个模板实际上是相同的。追踪到 Spring 代码,发现组件 1 的模板被解析为自动配置的stringRedisTemplate

手动调用RedisTemplate 的构造函数,然后调用它的afterPropertiesSet() 也不起作用,因为它抱怨找不到连接工厂。

我知道这个请求可能与在 Spring 应用程序中定义另一个 bean 没有太大区别,但不确定当前的 Spring-Data-Redis 集成对我来说最好的方法是什么。请帮忙,谢谢。

【问题讨论】:

    标签: spring-boot spring-data-redis


    【解决方案1】:

    您可以通过两种方式在一个 Spring Boot 应用程序中使用多个 RedisTemplates:

    1. 使用@Autowired @Qualifier("beanname") RedisTemplate myTemplate 命名bean 注入并使用@Bean(name = "beanname") 创建bean。
    2. 通过在RedisTemplate 上指定类型参数(例如@Autowired RedisTemplate<byte[], byte[]> byteTemplate@Autowired RedisTemplate<String, String> stringTemplate)进行类型安全注入。

    这是创建两个不同的代码:

    @Configuration
    public class Config {
    
        @Bean
        public RedisTemplate<String, String> stringTemplate(RedisConnectionFactory redisConnectionFactory) {
    
            RedisTemplate<String, String> stringTemplate = new RedisTemplate<>();
            stringTemplate.setConnectionFactory(redisConnectionFactory);
            stringTemplate.setDefaultSerializer(new StringRedisSerializer());
            stringTemplate.afterPropertiesSet();
    
            return stringTemplate;
        }
    
        @Bean
        public RedisTemplate<byte[], byte[]> byteTemplate(RedisConnectionFactory redisConnectionFactory) {
    
            RedisTemplate<byte[], byte[]> byteTemplate = new RedisTemplate<>();
            byteTemplate.setConnectionFactory(redisConnectionFactory);
            byteTemplate.afterPropertiesSet();
    
            return byteTemplate;
        }
    
    }
    

    HTH,马克

    【讨论】:

    • 非常感谢,这解决了我的问题。一个后续问题是,当我声明这样的 bean 时,Spring 如何知道为我传递所需的 RedisConnectionFactory?这可能是因为我对 Spring 机制还比较熟悉,如果你能教育我,不胜感激。
    • 只有一个连接工厂时,不用担心。如果有多个,你必须再次限定它们,否则你最终会得到NoUniqueBeanDefinitionException
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2018-03-17
    • 1970-01-01
    相关资源
    最近更新 更多