Today, with Springboot2 integration redis time, starting with a number of problems with the previous method. A check know Springboot2 use lettuce as the default redis client. So the configuration file other configuration parameters jedis of the configuration lettuce pool. Jedis client would like to add their own reliance on manual pom file the required jedis.
repeat: database: 0 host: 192.168.1.210 port: 6379 password: password lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0
Another problem is finished will report an error, probably
ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig
You need to rely on manually add the commons pool
<!-- redis lettuce pool 需要这个依赖 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.2</version> </dependency>
The last question is the custom RedisTempelate time, use the following code will complain Spring container can not find 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; } }
But in fact, this bean is there, because the default configuration redis class also uses the Bean. Project up and running is an error, RedisConnectionFactory IS required
Finally, when the automatic injection modify the default RedisTemplate properties, to solve this problem.
@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; } }