小编典典

Spring Redis-从application.properties文件读取配置

redis

我让Spring Redis使用spring-data-redis所有默认配置(例如localhostdefault port等)。

现在,我试图通过在application.properties文件中进行配置来进行相同的配置。但是我无法弄清楚应该如何准确地读取属性值来创建bean。

Redis配置文件

@EnableRedisHttpSession
@Configuration
public class SpringSessionRedisConfiguration {

@Bean
JedisConnectionFactory connectionFactory() {
    return new JedisConnectionFactory();
}

@Autowired
@Bean
RedisCacheManager redisCacheManager(final StringRedisTemplate stringRedisTemplate) {
    return new RedisCacheManager(stringRedisTemplate);
}

@Autowired
@Bean
StringRedisTemplate template(final RedisConnectionFactory connectionFactory) {
    return new StringRedisTemplate(connectionFactory);
}
}

application.properties中的标准参数

spring.redis.sentinel.master = themaster

spring.redis.sentinel.nodes = 192.168.188.231:26379

spring.redis.password = 12345

我尝试过的

  1. 我可以使用@PropertySource然后注入@Value并获取值。但是我不想这样做,因为那些属性不是我定义的,而是来自Spring的。
  2. 在本文档中,Spring Redis文档仅说明可以使用属性对其进行配置,但未显示具体示例。
  3. 我还遍历了Spring Data Redis API类,发现对RedisProperties我有帮助,但是仍然无法弄清楚如何确切地告诉Spring从属性文件中读取。

阅读 1127

收藏
2020-06-20

共1个答案

小编典典

您可以用来@PropertySource从application.properties或所需的其他属性文件中读取选项。请查看PropertySource用法示例用法spring-redis-
cache的
工作示例。或看看这个小样本:

@Configuration
@PropertySource("application.properties")
public class SpringSessionRedisConfiguration {

    @Value("${redis.hostname}")
    private String redisHostName;

    @Value("${redis.port}")
    private int redisPort;

    @Bean
    public static PropertySourcesPlaceholderConfigurer    propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(redisHostName);
        factory.setPort(redisPort);
        factory.setUsePool(true);
        return factory;
    }

    @Bean
    RedisTemplate<Object, Object> redisTemplate() {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        return redisTemplate;
    }

    @Bean
    RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
        return redisCacheManager;
    }
}

当前( 2015年12月 )中的 spring.redis.sentinel
选项application.properties仅提供RedisSentinelConfiguration以下有限的支持:

请注意,当前只有Jedis和生菜生菜支持Redis
Sentinel。

您可以在官方文档中阅读有关此内容的更多信息。

2020-06-20