Spring Redis - Read configuration from application.properties file

后端 未结 9 935
渐次进展
渐次进展 2020-12-25 13:46

I have Spring Redis working using spring-data-redis with all default configuration likes localhost default port and so on.

Now

9条回答
  •  -上瘾入骨i
    2020-12-25 14:23

    Here is an elegant solution to solve your issue :

    @Configuration
    @PropertySource(name="application", value="classpath:application.properties")
    public class SpringSessionRedisConfiguration {
    
        @Resource
        ConfigurableEnvironment environment;
    
        @Bean
        public PropertiesPropertySource propertySource() {
            return (PropertiesPropertySource) environment.getPropertySources().get("application");
        }
    
        @Bean
        public JedisConnectionFactory jedisConnectionFactory() {
            return new JedisConnectionFactory(sentinelConfiguration(), poolConfiguration());
        }
    
        @Bean
        public RedisSentinelConfiguration sentinelConfiguration() {
            return new RedisSentinelConfiguration(propertySource());
        }
    
        @Bean
        public JedisPoolConfig poolConfiguration() {
            JedisPoolConfiguration config = new JedisPoolConfiguration();
            // add your customized configuration if needed
            return config;
        }
    
        @Bean
        RedisTemplate redisTemplate() {
            RedisTemplate redisTemplate = new RedisTemplate();
            redisTemplate.setConnectionFactory(jedisConnectionFactory());
            return redisTemplate;
        }
    
        @Bean
        RedisCacheManager cacheManager() {
            return new RedisCacheManager(redisTemplate());
        }
    
    }
    

    so, to resume :

    • add a specific name for the @PropertySource
    • inject a ConfigurableEnvironment instead of Environment
    • get the PropertiesPropertySource in your ConfigurableEnvironment using the name you mentioned on your @PropertySource
    • Use this PropertySource object to construct your RedisSentinelConfiguration object
    • Don't forget to add 'spring.redis.sentinel.master' and 'spring.redis.sentinel.nodes' properties in you property file

    Tested in my workspace, Regards

提交回复
热议问题