RedisTemplate increment 错误:ERR value is not an integer or out of range解决

环境:
springboot+redis

    
        org.springframework.boot
        spring-boot-starter-parent
        1.4.0.RELEASE
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-redis
        
    

现象:
在以下代码执行到increment()方法的时候报错

@Autowired
    private RedisTemplate redisTemplate;
@RequestMapping("/hello")
public void hello(){
    ValueOperations valueOperations = redisTemplate.opsForValue();

    valueOperations.set("sk:0101:num",10);
}

@RequestMapping("/incr")
public void incr(){

    ValueOperations valueOperations = redisTemplate.opsForValue();

    valueOperations.increment("sk:0101:num",1);

    System.out.println(redisTemplate.opsForValue().get("sk:0101:num"));
}

原因:

也就是说,上述异常的意思是,增加的值(ERR)不是integer或者超出了integer范围,所以才报的错误。
根据建议,只有使用StringRedisSerializer序列化器才能使用incrment方法。那么为什么呢,为什么使用了StringRedisSerializer就可以而使用默认序列化器就不行呢。 实验

我们都知道序列化器是,将key或者value序列化成流,存储到redis。首先看一下RedisSerializer接口
结果
RedisTemplate increment 错误:ERR value is not an integer or out of range解决_第1张图片RedisTemplate increment 错误:ERR value is not an integer or out of range解决_第2张图片RedisTemplate increment 错误:ERR value is not an integer or out of range解决_第3张图片
可见:
GenericJackson2JsonRedisSerializer、Jackson2JsonRedisSerializer是先将对象转为json,然后再保存到redis,所以,1在redis中是字符串1,所以无法进行加1 JdkSerializationRedisSerializer使用的jdk对象序列化,序列化后的值有类信息、版本号等,所以是一个包含很多字母的字符串,所以根本无法加1,这个序列化器跟memcache的序列化规则很像memcache怎样存储的对象 GenericToStringSerializer、StringRedisSerializer将字符串的值直接转为字节数组,所以保存到redis中是数字,所以可以进行加1 ;
通过以下代码配置redistemplate的序列化方式之后就可以顺利的执行increment了;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }


/**
 * 设置 redisTemplate 的序列化设置
 * @param redisConnectionFactory
 * @return
 */
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    // 1.创建 redisTemplate 模版
    RedisTemplate template = new RedisTemplate<>();
    // 2.关联 redisConnectionFactory
    template.setConnectionFactory(redisConnectionFactory);
    // 3.创建 序列化类
    GenericToStringSerializer genericToStringSerializer = new GenericToStringSerializer(Object.class);
    // 6.序列化类,对象映射设置
    // 7.设置 value 的转化格式和 key 的转化格式
    template.setValueSerializer(genericToStringSerializer);
    template.setKeySerializer(new StringRedisSerializer());
    template.afterPropertiesSet();
    return template;
    }
}

你可能感兴趣的:(RedisTemplate increment 错误:ERR value is not an integer or out of range解决)