将Redis 默认序列化规则(JDK)改写为Json格式

1. 默认JDK序列化测试

查看源代码:
Redis默认使用JDK的序列化规则:

在这里插入图片描述

连接上Redis后,传入对象进行测试:
Employee是一个实体类,包括id、lastName、email、gender等属性。
关于连接Redis等配置,就里就不过多阐述。。。
博主的操作环境是再SpringBoot:

如果需要下载测试代码:https://github.com/GYT0313/SpringBoot-Learning/tree/master/spring-boot-cache

测试代码:
在这里插入图片描述
运行,查看Redis数据库:
在这里插入图片描述

2. 改写为Json格式

首先需要配置我们自己的Redis序列化规则:
通过查看Redis的自动配置源代码,只需要在我们的自动配置中模仿即可:
在这里插入图片描述

创建我们自己的配置:
在这里插入图片描述

package com.gyt.springbootcache.config;

import com.gyt.springbootcache.bean.Employee;
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;

@Configuration
public class MyRedisConfig {
    @Bean
    public RedisTemplate<Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(ser);
        return template;
    }
}

再次测试:
在这里插入图片描述
运行查看结果:
在这里插入图片描述

完!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值