redis如何進行序列化?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
序列化最終的目的是為了對象可以跨平臺存儲,和進行網絡傳輸。而我們進行跨平臺存儲和網絡傳輸的方式就是IO,而我們的IO支持的數據格式就是字節數組。
通過上面我想你已經知道了凡是需要進行“跨平臺存儲”和”網絡傳輸”的數據,都需要進行序列化。
本質上存儲和網絡傳輸 都需要經過 把一個對象狀態保存成一種跨平臺識別的字節格式,然后其他的平臺才可以通過字節信息解析還原對象信息。
redis序列化方式對比:
redis的默認方式是JdkSerializationRedisSerializer
JdkSerializationRedisSerializer: 使用JDK提供的序列化功能。
優點是反序列化時不需要提供類型信息(class),但缺點是需要實現Serializable接口,還有序列化后的結果非常龐大,是JSON格式的5倍左右,這樣就會消耗redis服務器的大量內存。
Jackson2JsonRedisSerializer: 使用Jackson庫將對象序列化為JSON字符串。
優點是速度快,序列化后的字符串短小精悍,不需要實現Serializable接口。
但缺點也非常致命,那就是此類的構造函數中有一個類型參數,必須提供要序列化對象的類型信息(.class對象)。 通過查看源代碼,發現其只在反序列化過程中用到了類型信息。
問題:使用默認的JDK序列化方式,在RDM工具中查看k-v值時會出現“亂碼”,不方便查看。
解決:自定義系列化方式,使用Jackson2JsonRedisSerializer
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis配置
*
* @author LinJie
*/
@Configuration
public class RedisConfig {
/**
* Redis repository redis repository.
*
* @param redisTemplate the redis template
* @return the redis repository
*/
@Bean
public RedisRepository redisRepository(RedisTemplate redisTemplate) {
// 使用Jackson2JsonRedisSerialize 替換默認序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
redisTemplate.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return new RedisRepository(redisTemplate);
}
}關于redis如何進行序列化問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。