不从属性文件中选择Redis的属性

时间:2019-05-20 11:57:26

标签: spring-boot spring-data-redis

我已经在Spring Boot应用程序中配置了Redis,并将其一些属性放在application.properties文件中。但它采用默认属性(localhost:6379)

这是配置

2

这是我在属性文件中的属性

(3,4,5)

3 个答案:

答案 0 :(得分:0)

我已经使用RedisStandaloneConfiguration设置属性。现在工作正常

@Bean
    JedisConnectionFactory jedisConnectionFactory() {

        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName("localhost");
        redisStandaloneConfiguration.setPort(6379);
        redisStandaloneConfiguration.setDatabase(0);
        redisStandaloneConfiguration.setPassword(RedisPassword.of("password"));

        JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
        jedisClientConfiguration.connectTimeout(Duration.ofSeconds(60));// 60s connection timeout

        JedisConnectionFactory jedisConFactory = new JedisConnectionFactory(redisStandaloneConfiguration,
                jedisClientConfiguration.build());

        return jedisConFactory;
    }

答案 1 :(得分:0)

在配置中添加PropertySource注释

@Configuration
@EnableRedisRepositories("com.demo.redis.repository")
@PropertySource("classpath:application.properties")
public class RedisDataSourceConfig {


@Bean
public JedisConnectionFactory jedisConnectionFactory() {
    log.debug("Create Jedis Connection Factory");
    return new JedisConnectionFactory();
}


@Bean
public RedisTemplate<String, Object> redisTemplate() {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(jedisConnectionFactory());
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new JdkSerializationRedisSerializer());
    template.setHashKeySerializer(template.getKeySerializer());
    template.setHashValueSerializer(template.getValueSerializer());
    return template;
}


@Bean
public RedisTemplate<String, Object> jsonRedisTemplate() {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(jedisConnectionFactory());
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
    redisTemplate.setHashKeySerializer(redisTemplate.getKeySerializer());
    redisTemplate.setHashValueSerializer(redisTemplate.getValueSerializer());
    return redisTemplate;
}

}

答案 2 :(得分:0)

您应该为 JedisConnectionFactory 使用 @Bean 而不是使用 @Autowired 批注。使用以下代码:

@Autowired
private JedisConnectionFactory jedisConnectionFactory;

然后在您的 redisTemplate() 方法中调用:

template.setConnectionFactory(jedisConnectionFactory);

现在,jedisConnectionFactory 将使用您的 application.properties,只要它在标准路径中可用:src/main/resources