Redis指定自定义对象序列化

2022-11-22 20:05:40 浏览数 (1)

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

修改RedisConfig中的redistemplate@bean

代码语言:javascript复制
    @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;
    }

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

代码语言:javascript复制
@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);
    }

Post Views: 216

0 人点赞