Redis数据序列化器

Redis序列化

Redis 数据序列化器用于将数据在存储到 Redis 中时进行序列化(编码)和反序列化(解码)。

RedisTemplate的两种序列化实践方案:

方案一:

  • 自定义RedisTemplate

  • 修改RedisTemplate的序列化器为GenericJackson2JsonRedisSerializer

方案二:

  • 使用StringRedisTemplate

  • 写入Redis时,手动把对象序列化为JSON

  • 读取Redis时,手动把读取到的JSON反序列化为对象

方案三“:

  • 自定义RedisTemplate

  • 修改RedisTemplate的序列化器为FastJsonRedisSerializer

方案一

RedisTemplate可以接收任意Object作为值写入Redis:

        // 写入一条String数据
        redisTemplate.opsForValue().set("name", "李白");
        // 获取string数据
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println("name = " + name);

只不过写入前会把Object序列化为字节形式,默认是采用JDK序列化,得到的结果是这样的:

缺点:

  • 可读性差
  • 内存占用较大

我们可以自定义RedisTemplate的序列化方式,代码如下:

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){
        // 创建RedisTemplate对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置连接工厂
        template.setConnectionFactory(connectionFactory);
        // 创建JSON序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = 
            							new GenericJackson2JsonRedisSerializer();
        // 设置Key的序列化
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置Value的序列化
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);
        // 返回
        return template;
    }
}

这里采用了JSON序列化来代替默认的JDK序列化方式。最终结果如图:

当我们存的数据是一个对象时:

        Student student = new Student("李白",28);
        // 写入一条String数据
        redisTemplate.opsForValue().set("student", student);
        // 获取string数据
        Object name = redisTemplate.opsForValue().get("student");
        System.out.println("name = " + name);

能将Java对象自动的序列化为JSON字符串,并且查询时能自动把JSON反序列化为Java对象。不过,其中记录了序列化时对应的class名称,目的是为了查询时实现自动反序列化。这会带来额外的内存开销。  

方案二 

为了在反序列化时知道对象的类型,JSON序列化器会将类的class类型写入json结果中,存入Redis,会带来额外的内存开销。为了减少内存的消耗,我们可以采用手动序列化的方式,换句话说,就是不借助默认的序列化器,而是我们自己来控制序列化的动作,同时,我们只采用String的序列化器,这样,在存储value时,我们就不需要在内存中就不用多存储数据,从而节约我们的内存空间

     private static final ObjectMapper mapper = new ObjectMapper();

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Test
    void testSaveUser() throws JsonProcessingException {
        // 创建对象
        Student student = new Student("李白",28);
        // 手动序列化
        String json = mapper.writeValueAsString(student);
        // 写入数据
        stringRedisTemplate.opsForValue().set("student", json);

        // 获取数据
        String jsonUser = stringRedisTemplate.opsForValue().get("user:200");
        // 手动反序列化
        Student user1 = mapper.readValue(jsonUser, Student.class);
        System.out.println("user1 = " + user1);
    }

此时我们再来看一看存储的数据,小伙伴们就会发现那个class数据已经不在了,节约了我们的空间~  

方案三

方案二每次的手动序列化十分麻烦,我们可以指定序列化器为FastJsonRedisSerializer

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
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.StringRedisSerializer;
 
@Configuration
public class RedisConfig {
 
    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        // 创建JSON序列化工具
        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);
 
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
 
        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
 
        template.afterPropertiesSet();
        return template;
    }
}

测试

         Student student = new Student("厉害", 22);
        // 写入一条String数据
        redisTemplate.opsForValue().set("student", student);
        // 获取string数据
        Object name = redisTemplate.opsForValue().get("student");
        System.out.println("student = " + name);

结果 

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值