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; }