redis通用配置類的使用詳解
更新時間:2025年08月02日 10:58:42 作者:天珩
Redis通用配置類通過設置JSON序列化器,解決Spring?Boot中RedisTemplate默認使用byte數(shù)組存儲數(shù)據(jù)導致的不可讀問題,使數(shù)據(jù)以JSON字符串形式保存,便于查看與調(diào)試
redis通用配置類
作用 處理Springboot使用 RedisTemplate過程中的編碼問題
現(xiàn)象如下,看數(shù)據(jù)的時候不方便

所以添加一下的配置類之后,就可以了
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 指定在轉(zhuǎn)成json的時候的一些轉(zhuǎn)換規(guī)則
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中(可以不設置,使用默認規(guī)則)
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//RedisTemplate默認的序列化方式使用的是JDK的序列化
//設置了key的序列化方式
template.setKeySerializer(new StringRedisSerializer());
//設置了value的序列化方式
template.setValueSerializer(jackson2JsonRedisSerializer);
return template;
}
}
原理
設置其他的序列化方式使用json形式
RedisTemplate,默認序列化的時候,用的RedisTemplate里面的一個RedisSerializer對象的string方法

看string()方法


轉(zhuǎn)成了byte[] bytes
就是說最終是轉(zhuǎn)成了字節(jié)流
所以并不是通過json串的方式,這樣出來的結果就不是json串
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Redis 中spark參數(shù)executor-cores引起的異常解決辦法
這篇文章主要介紹了Redis 中spark參數(shù)executor-cores引起的異常解決辦法的相關資料,需要的朋友可以參考下2017-03-03
Redis報錯“NOAUTH Authentication required”兩種解決方案
Redis提供了一個命令行工具redis-cli,它允許你直接連接到Redis服務器,如果你知道Redis服務器的密碼,你可以在連接時直接提供它,本文給大家介紹連接了Redis報錯“NOAUTH Authentication required”兩種解決方案2024-05-05

