springboot实现redis序列化
如果我们使用redis可视化工具查看k/v时,都是乱码形式,
所以需要使用Jackson进行JSON格式的序列化和反序列才能看到具体数值。
@EnableRedisHttpSession是把session整合到redis中,需要引入以下的maven包
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--session整合到redis-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
/**
* redis配置类,序列化
*/
@Configuration
@EnableRedisHttpSession
public class RedisConfig {
/**
* redisTemplate 序列化配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// key 序列化
template.setKeySerializer(new StringRedisSerializer());
// value 序列化
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// hash key 序列化
template.setHashKeySerializer(new StringRedisSerializer());
// hash value 序列化
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
// 注入连接工厂
template.setConnectionFactory(factory);
return template;
}
/**
* 设置spring session redis 序列化方式
* @return
*/
@Bean
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
}
目录