当前位置: 代码网 > it编程>数据库>Redis > redis通用配置类的使用详解

redis通用配置类的使用详解

2025年08月02日 Redis 我要评论
redis通用配置类作用 处理springboot使用 redistemplate过程中的编码问题现象如下,看数据的时候不方便所以添加一下的配置类之后,就可以了package com.htb.beid

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串

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com