redis 通用配置類
作用 處理Springboot使用 RedisTemplate過程中的編碼問題
現象如下,看數據的時候不方便
所以添加一下的配置類之後,就可以了
package com.htb.beidawebspringboot10redis.config;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
/**
* @Description:Redis通用配置類
* @Author 16221
* @Date 2020/4/23
**/
@Configuration
public class RedisConfig {
@Bean
//不指定id的話bean 的id就是方法名
//返回結果就是spring中管理的bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
//ObjectMapper 指定在轉成json的時候的一些轉換規則
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//把自定義objectMapper設置到jackson2JsonRedisSerializer中(可以不設置,使用默認規則)
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//RedisTemplate默認的序列化方式使用的是JDK的序列化
//設置了key的序列化方式
template.setKeySerializer(new StringRedisSerializer());
//設置了value的序列化方式
template.setValueSerializer(jackson2JsonRedisSerializer);
return template;
}
}
原理:設置其他的序列化方式使用json形式
RedisTemplate,默認序列化的時候,用的RedisTemplate裏面的一個RedisSerializer對象的string方法
下面看string()方法
轉成了byte[] bytes
就是說最終是轉成了字節流
所以並不是通過json串的方式,這樣出來的結果就不是json串