springboot 2.1启动,redis报错Failed to instantiat ... java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig
SpringBoot 2.1.1 集成 redis,在启动时报错信息如下:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method 'redisConnectionFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig
解决方案:
引入连接池依赖
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.8.0</version> </dependency
另外:
由于从 springboot2.0 开始,spring-boot-starter-data-redis 默认使用 lettuce 代替 Jedis,因此需要把配置文件中 redis 配置中的 jedis 改为 lettuce,
如下
#rediss
spring.redis.cluster.nodes=
spring.redis.timeout=
spring.redis.lettuce.pool.max-wait=
spring.redis.lettuce.pool.max-active=
spring.redis.lettuce.pool.max-idle=
spring.redis.lettuce.pool.min-idle=
如果使用 jedis,需修改 pom 文件
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
RedisConfig.java
@Bean public RedisConnectionFactory redisCF() { JedisConnectionFactory rcf = new JedisConnectionFactory(); rcf.setHostName("127.0.0.1"); rcf.setPort(6379); return rcf; }@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
return template;
}
如果使用 Lettuce ,则 pom 文件如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
RedisConfig.java
@Bean public RedisConnectionFactory redisCF() { // JedisConnectionFactory rcf = new JedisConnectionFactory(); LettuceConnectionFactory rcf = new LettuceConnectionFactory(); rcf.setHostName("127.0.0.1"); rcf.setPort(6379); // rcf.setPassword(); return rcf; }@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
return template;
}