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串
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论