Add dependency
<!-- spring boot2.0 Later, the default redisConnectionFactory by LettuceConnectionFactory,I want to continue using it here. jedis,Just do it. exclusion --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </exclusion> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <!-- Add to jackson Dependence is used to solve problems redis Serialization and deserialization --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency>
Add configuration
## Connection property configuration spring.redis.host= spring.redis.database= spring.redis.port= spring.redis.password= spring.redis.timeout= ## Connection pool configuration spring.redis.jedis.pool.max-active= spring.redis.jedis.pool.max-idle= spring.redis.jedis.pool.max-wait= spring.redis.jedis.pool.min-idle=
The connection property configuration above and spring data redis have all been defaulted. If the connection data is the same as the default configuration, it may not need to be filled in. Although the connection pool configuration below has also been defaulted, if all of them are not filled in, it will cause the situation that the connection pool is not used.
Injecting bean s to solve serialization problems
By default, redisTemplate uses JdkSerialization RedisSerializer, which does not support serialization of custom objects.
@Configuration public class RedisConfig { @Bean public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory connectionFactory){ //Setting serialization Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // Configure redisTemplate RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(connectionFactory); redisTemplate.setKeySerializer(jackson2JsonRedisSerializer); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
Injecting RedisTemplate for redis operation
@Autowired private RedisTemplate redisTemplate; redisTemplate.opsForValue().set("key", "value");