【Springboot】Springboot2 集成 redis 踩坑

今天用Springboot2集成redis的時候,一開始是用之前的方法出了不少問題。一查才知道Springboot2使用 lettuce 做爲默認的redis client。因此配置文件裏別配置jedis的參數了,配置lettuce pool。 還想用 jedis 的須要本身在 pom 文件手動添加 jedis client 的依賴。redis

redis: database: 0 host: 192.168.1.210 port: 6379 password: password lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0

完了還有一個問題就是會報一個錯誤, 大概就是 apache

ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig

須要手動添加 commons pool 的依賴app

<!-- redis lettuce pool 須要這個依賴 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.2</version>
        </dependency>

 

最後一個問題就是在自定義 RedisTempelate 的時候, 使用如下代碼會報錯 Spring 容器中找不到 RedisConnectionFactory ui

@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 requiredthis

 

 

最後是在自動注入的時候修改了默認RedisTemplate 的 屬性,解決了這個問題。spa

@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; } }
相關文章
相關標籤/搜索