spring-data-redis中同时使用set()、get()、increment()的问题

1.问题描述

最近开发代码,使用redis时,遇到一个有意思的问题,问题代码如下:

class Test {

        /**
         * redis操作句柄
         */
        @Autowired
        private RedisTemplate redisTemplate;

        public void test() {
            // 先set key1,再get key1没有问题,但是再increment就会报错
            redisTemplate.opsForValue().set("key1", 1);
            Integer val1 = redisTemplate.opsForValue().get("key1");
            Long incr1 = redisTemplate.opsForValue().increment("key1");

            // 先increment key2(key2之前不存在),再get key2就会报错
            Long incr2 = redisTemplate.opsForValue().increment("key2");
            Integer val2 = redisTemplate.opsForValue().get("key2");
        }
}

如代码注释描述:

  • 问题1:先set key1,再get key1没有问题,但是再increment就会报错,报错内容如下:
org.springframework.dao.InvalidDataAccessApiUsageException: ERR value is not an integer or out of range; nested exception is redis.clients.jedis.exceptions.JedisDataException: ERR value is not an integer or out of range
    at org.springframework.data.redis.connection.jedis.JedisExceptionConverter.convert(JedisExceptionConverter.java:69) ~[spring-data-redis-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.redis.connection.jedis.JedisExceptionConverter.convert(JedisExceptionConverter.java:42) ~[spring-data-redis-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.redis.PassThroughExceptionTranslationStrategy.translate(PassThroughExceptionTranslationStrategy.java:44) ~[spring-data-redis-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.redis.FallbackExceptionTranslationStrategy.translate(FallbackExceptionTranslationStrategy.java:42) ~[spring-data-redis-2.3.6.RELEASE.jar:2.3.6.RELEASE]
  • 问题2:先increment key2(key2之前不存在),再get key2就会报错,报错内容如下:
org.springframework.data.redis.serializer.SerializationException: 反序列化对象失败; nested exception is com.caucho.hessian.io.HessianProtocolException: unknown code for readObject at 0x31 (1)
    at tech.joymo.framework.redis.sserializer.HessianSerializer.deserialize(HessianSerializer.java:61) ~[joymo-framework-redis-1.0-20210202.122946-5.jar:1.0-SNAPSHOT]
    at org.springframework.data.redis.core.AbstractOperations.deserializeValue(AbstractOperations.java:335) ~[spring-data-redis-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.redis.core.AbstractOperations$ValueDeserializingRedisCallback.doInRedis(AbstractOperations.java:61) ~[spring-data-redis-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:228) ~[spring-data-redis-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:188) ~[spring-data-redis-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:96) ~[spring-data-redis-2.3.6.RELEASE.jar:2.3.6.RELEASE]
    at org.springframework.data.redis.core.DefaultValueOperations.get(DefaultValueOperations.java:53) ~[spring-data-redis-2.3.6.RELEASE.jar:2.3.6.RELEASE]

2.问题分析

分析上面的报错内容可知,两个问题都是redis存储的数据格式有问题导致,但是为什么会有这种问题呢?

查阅spring文档(Spring Data Redis 10.8. Serializers)可知,Spring对Redis常用序列化的策略有两种

其中RedisTemplate的默认序列化策略是JdkSerializationRedisSerializer,而StringRedisTemplate的序列化策略是StringRedisSerializer

RedisTemplate是使用的JdkSerializationRedisSerializer序列化,序列化后的值包含了对象信息,版本号,类信息等,是一串字符串,所以无法进行数值自增操作。

而StringRedisTemplate序列化策略是字符串的值直接转为字节数组,所以存储到redis中是数值,所以可以进行自增操作。

所以,因为代码中注入的是RedisTemplate实现,使用了JdkSerializationRedisSerializer作为序列化方法,所以set和get的时候都会进行序列化和反序列化,而increment操作不会进行序列化,所以导致上述两个问题。

3.解决办法

解决方法很简单,JdkSerializationRedisSerializer序列化导致的问题,那么将序列化换成StringRedisSerializer即可。代码如下,直接注入RedisTemplate<String, String>StringRedisTemplate都可以获得StringRedisTemplate的实例,从而解决问题。

class Test {

        /**
         * redis操作句柄
         */
        @Autowired
        private RedisTemplate<String, String> redisTemplate;

        /**
         * redis操作句柄
         */
        @Autowired
        private StringRedisTemplate stringRedisTemplate;

        public void test() {
            // 先set key1,再get key1没有问题,但是再increment就会报错
            redisTemplate.opsForValue().set("key1", "1");
            String val1 = redisTemplate.opsForValue().get("key1");
            String incr1 = redisTemplate.opsForValue().increment("key1");

            // 先increment key2(key2之前不存在),再get key2就会报错
            String incr2 = redisTemplate.opsForValue().increment("key2");
            String val2 = redisTemplate.opsForValue().get("key2");
        }
}

或者使用redisTemplate前设置序列化策略

代码1:

class Test {

        /**
         * redis操作句柄
         */
        @Autowired
        private RedisTemplate redisTemplate;

        public void test() {
            redisTemplate.setValueSerializer(new StringRedisSerializer());
            // 先set key1,再get key1没有问题,但是再increment就会报错
            redisTemplate.opsForValue().set("key1", "1");
            String val1 = (String) redisTemplate.opsForValue().get("key1");
            Long incr1 = redisTemplate.opsForValue().increment("key1");

            // 先increment key2(key2之前不存在),再get key2就会报错
            Long incr2 = redisTemplate.opsForValue().increment("key2");
            String val2 = (String) redisTemplate.opsForValue().get("key2");
        }
    }

代码2:

    class Test {

        /**
         * redis操作句柄
         */
        @Autowired
        private RedisTemplate redisTemplate;

        public void test() {
            redisTemplate.setValueSerializer(new GenericToStringSerializer<>(Integer.class));
            // 先set key1,再get key1没有问题,但是再increment就会报错
            redisTemplate.opsForValue().set("key1", 1);
            Integer val1 = (Integer) redisTemplate.opsForValue().get("key1");
            Long incr1 = redisTemplate.opsForValue().increment("key1");

            // 先increment key2(key2之前不存在),再get key2就会报错
            Long incr2 = redisTemplate.opsForValue().increment("key2");
            Integer val2 = (Integer) redisTemplate.opsForValue().get("key2");
        }
    }

代码3:

class Test {

        /**
         * redis操作句柄
         */
        @Autowired
        private RedisTemplate<String, Integer> redisTemplate;

        public void test() {
            redisTemplate.setValueSerializer(new StringRedisSerializer());
            // 先set key1,再get key1没有问题,但是再increment就会报错
            redisTemplate.opsForValue().set("key1", 1);
            Integer val1 = redisTemplate.opsForValue().get("key1");
            Long incr1 = redisTemplate.opsForValue().increment("key1");

            // 先increment key2(key2之前不存在),再get key2就会报错
            Long incr2 = redisTemplate.opsForValue().increment("key2");
            Integer val2 = redisTemplate.opsForValue().get("key2");
        }
    }
03-05 21:05