美文网首页
Redis序列化问题

Redis序列化问题

作者: java_飞 | 来源:发表于2022-08-13 14:34 被阅读0次

    描述

    coding过程中,我们在使用redis进行存取Long或Byte型数据时,发现存进去的Long数据,出来的却是Integer数据,当我们接收是使用Long或Byte取进行接收时就会报类型转换错误。

    前提:当我们设置的redis的value序列化不是jdk自带的序列化时才会报这个错。

    具体原理可以详见链接:https://blog.51cto.com/u_3631118/3121370

    代码demo

    redis序列化代码

     @Bean
        public RedisTemplate<?, ?> redisTemplate(RedisConnectionFactory connectionFactory) {
            RedisTemplate template = new RedisTemplate<>();
            template.setConnectionFactory(connectionFactory);
            template.setValueSerializer(getJackson2JsonRedisSerializer());
            // 使用StringRedisSerializer来序列化和反序列化redis的key值
            template.setKeySerializer(getStringRedisSerializer());
            template.setHashKeySerializer(getStringRedisSerializer());
            template.setHashValueSerializer(getJackson2JsonRedisSerializer());
            template.afterPropertiesSet();
            RedisCacheUtils.setRedisTemplate(template);
            return template;
        }
    

    错误使用

      /**
       * 新增
       */
       private Long get(String no) {
            String key = getKey(date);
            Long value = RedisCacheUtils.getHash(key, no);
            return value == null ? 0 :value;
        }
         /**
         * 减少
         *
         * @param driverNo
         * @param orderDate
         * @return 操作后的数量
         */
        private void hInc(String no) {
          RedisCacheUtils.hIncrement(key, driverNo, -1L);
        }
    

    正确使用

     /**
       * 新增
       */
       private Integer get(String no) {
            String key = getKey(date);
            Integer value = RedisCacheUtils.getHash(key, no);
            return value == null ? 0 :value;
        }
         /**
         * 减少
         *
         * @param driverNo
         * @param orderDate
         * @return 操作后的数量
         */
        private void hInc(String no) {
          RedisCacheUtils.hIncrement(key, driverNo, -1);
        }
          /**
         * 减少
         *
         * @param driverNo
         * @param orderDate
         * @return 操作后的数量
         */
        private void hInc(String no) {
          RedisCacheUtils.hIncrement(key, driverNo, -1L);
        }
    
           public Long getTimestamp(String orderNo) {
            return RedisCacheUtils.get(getKey(orderNo));
        }
    
        public void setTimestamp(String orderNo) {
             RedisCacheUtils.set(getKey(orderNo),           Instant.now().toEpochMilli(),1000, TimeUnit.MINUTES);
        }
    

    相关文章

      网友评论

          本文标题:Redis序列化问题

          本文链接:https://www.haomeiwen.com/subject/pmqhgrtx.html