我让 Spring Redis 使用 spring-data-redis
和所有默认配置(如 localhost
默认 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
我试过了,
@PropertySource
然后注入(inject) @Value
并获取值。但我不想这样做,因为这些属性不是我定义的,而是来自 Spring。RedisProperties
应该可以帮助我,但仍然无法弄清楚如何告诉 Spring 从属性文件中读取。最佳答案
您可以使用 @PropertySource
从 application.properties 或其他您想要的属性文件中读取选项。请看PropertySource usage example和工作example of usage 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 月),application.properties
中的 spring.redis.sentinel 选项对 RedisSentinelConfiguration 的支持有限
:
Please note that currently only Jedis and lettuce Lettuce support Redis Sentinel.
您可以在 official documentation 中了解更多相关信息.
关于java - Spring Redis - 从 application.properties 文件中读取配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34201135/