今天用Springboot2集成redis的时候,一开始是用以前的方法出了很多问题。一查才知道Springboot2使用 lettuce 作为默认的redis client。所以配置文件里别配置jedis的参数了,配置lettuce pool。 还想用 jedis 的需要自己在 pom 文件手动添加 jedis client 的依赖。
redis: database: 0 host: 192.168.1.210 port: 6379 password: password lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0
完了还有一个问题就是会报一个错误, 大概就是
ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig
需要手动添加 commons pool 的依赖
<!-- redis lettuce pool 需要这个依赖 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.2</version> </dependency>
最后一个问题就是在自定义 RedisTempelate 的时候, 使用以下代码会报错 Spring 容器中找不到 RedisConnectionFactory
@Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisConfig { @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); redisSerializer.setObjectMapper(mapper); template.setValueSerializer(redisSerializer); template.setKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } }
但是实际上这个bean是存在的,因为 redis 的默认配置类也使用了这个Bean。 项目跑起来也是报错,RedisConnectionFactory is required
最后是在自动注入的时候修改了默认RedisTemplate 的 属性,解决了这个问题。
@Component public class RedisCenter { private RedisTemplate<Object, Object> redisTemplate; public void expire(Object key, Object value, long time, TimeUnit unit) { redisTemplate.opsForValue().set(key, value, time, unit); } public Object get(Object key) { return redisTemplate.opsForValue().get(key); } @Autowired public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) { Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); redisSerializer.setObjectMapper(mapper); redisTemplate.setValueSerializer(redisSerializer); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.afterPropertiesSet(); this.redisTemplate = redisTemplate; } }