Spring boot configuration stand-alone version:
redis spring boot version:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.6.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> <spring.version>4.1.7.RELEASE</spring.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> //Add redis dependencies <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
redis.properties configuration:
# REDIS (RedisProperties) # Redis database index (default 0) spring.redis.database=0 # Redis server address spring.redis.host=xx.xx.xx.xx # Redis server connection port spring.redis.port=6379 # Redis server connection password (default is empty) spring.redis.password=123456 # Connection timeout (ms) spring.redis.timeout=0
java code:
// get connection @Bean public JedisConnectionFactory redisConnectionFactory() { JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setHostName(host); factory.setPort(port); factory.setPassword(password); factory.setTimeout(timeout); return factory; } //Set the redis template and its sequence method @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(factory); template.setHashKeySerializer(new StringRedisSerializer()); template.setKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new JdkSerializationRedisSerializer()); //setSerializer(template); // Set the serializer so that ReportBean does not need to implement the Serializable interface template.afterPropertiesSet(); return template; } private void setSerializer(StringRedisTemplate template) { 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); template.setValueSerializer(jackson2JsonRedisSerializer); }
Notice:
There is a lot of talk on the Internet: I use this jackson2JsonRedisSerializer class to serialize data, but the data structure I use is more complicated. Generally, there are json arrays in json. There is no problem with the outer json conversion of this class, but there is a problem with the internal json conversion. So use JdkSerializationRedisSerializer for serialization