欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot配置单机版redis

程序员文章站 2022-05-28 13:59:16
...

spring boot配置单机版:

   redis spring boot版本:

  

<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>
//添加redis的依赖
<dependency>  
    	<groupId>org.springframework.boot</groupId>  
    	<artifactId>spring-boot-starter-redis</artifactId>  
</dependency> 

 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<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); // 设置序列化工具,这样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进行序列化

 

相关标签: spring boot redis