spring boot配置单机版redis

spring boot配置单机版:

   redis spring boot版本:

  


	org.springframework.boot
	spring-boot-starter-parent
	1.2.6.RELEASE


	1.8
	4.1.7.RELEASE
	UTF-8

//添加redis的依赖
  
    	org.springframework.boot  
    	spring-boot-starter-redis  
 

 redis.properties配置:

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=xx.xx.xx.xx
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# 连接超时时间(毫秒)
spring.redis.timeout=0 

 java代码:

 //获取连接	
@Bean
public JedisConnectionFactory redisConnectionFactory() {
	JedisConnectionFactory factory = new JedisConnectionFactory();
	
	factory.setHostName(host);
	factory.setPort(port);
	factory.setPassword(password);
	factory.setTimeout(timeout);
	return factory;
	}
//设置redis模板,及其序列方式
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
	RedisTemplate template = new RedisTemplate();
	template.setConnectionFactory(factory);
	template.setHashKeySerializer(new StringRedisSerializer());
	template.setKeySerializer(new StringRedisSerializer());
	template.setHashValueSerializer(new JdkSerializationRedisSerializer());
		//setSerializer(template); // 设置序列化工具,这样ReportBean不需要实现Serializable接口
	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);
}

注意:

网上很多说:用这个jackson2JsonRedisSerializer类来序列化数据,但是我用的数据结构比较复杂,一般json中还有json数组等,用这个类外层json转换没有问题,但是内部json转换就有问题。所以用了JdkSerializationRedisSerializer进行序列化

 

你可能感兴趣的:(java,spring,boot,redis)