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
欢迎来到Diuut的个人博客,这里是我的一些零零碎碎的知识汇总,希望有能帮到你的内容。 | 蜀ICP备2021011635号-1 | Copyright © 2024 Diuut. All Rights Reserved.