Site Overlay

Redis指定自定义对象序列化

需求:

替换redisTemplate中的默认序列化方式,可以不用强转得到指定对象

修改RedisConfig中的redistemplate@bean

    @Bean(name = "stuRedisTemplate")
    public RedisTemplate<String, Student> stuRedisTemplate(RedisConnectionFactory redisConnectionFactory){
        log.info("objectTemplate");
        RedisTemplate<String, Student> redisTemplate = new RedisTemplate<String, Student>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
//原本是GenericJackson2JsonRedisSerializer()
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

然后在调用处指定调用方式

@Resource(name = "stuRedisTemplate")
     RedisTemplate<String, Student> redisTemplate;

     @Test
     public void test5() {
        Optional<Student> optionalStudent = studentDao.findById(4);
        Student student = optionalStudent.get();
        log.info("student:{}", student);
        redisTemplate.opsForValue().set("test-students:3",student );

        Student student1 =  redisTemplate.opsForValue().get("test-students:3");
        //此处就不用强转,并且redis中的也是标准的json字符串,可读性也好
        log.info("student1: {}",student1);
    }

发表评论

电子邮件地址不会被公开。 必填项已用*标注

A beliving heart is your magic My heart
Copyright © 2020 Diuut. All Rights Reserved. | Catch Vogue by Catch Themes