用spring-boot解决JedisConnectionFactory was not initialized through afterPropertiesSet()这个问题
时间: 2024-01-21 12:17:46 浏览: 504
在使用Jedis连接Redis时,遇到“JedisConnectionFactory was not initialized through afterPropertiesSet()”这个问题,通常是因为JedisConnectionFactory没有被正确初始化。可以尝试使用以下方法解决该问题:
1. 确认已经在pom.xml文件中引入了spring-boot-starter-data-redis依赖。
2. 在Redis配置类中使用@Bean注解来创建JedisConnectionFactory实例,并且将其作为参数传递给RedisTemplate的构造函数。
```java
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName(host);
jedisConnectionFactory.setPort(port);
jedisConnectionFactory.setPassword(password);
return jedisConnectionFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
```
3. 在application.properties或application.yml文件中配置Redis连接信息。
```yaml
spring:
redis:
host: localhost
port: 6379
password: xxxx
```
通过以上步骤,可以使用Spring Boot解决“JedisConnectionFactory was not initialized through afterPropertiesSet()”这个问题。
阅读全文