问题描述
使用的RedisTemplate,做读写操作时候,都是要经过序列化和反序列化。最近遇到了一个问题,使用incr计数,存进去了一个数字(int类型),但是因为是序列化之后存进去的,调用incr方法时候报错了:org.springframework.dao.InvalidDataAccessApiUsageException:ERRvalueisnotanintegeroroutofrange;nestedexceptionisredis.clients.jedis.exceptions.JedisDataException:ERRvalueisnotanintegeroroutofrangeatorg.springframework.data.redis.connection.jedis.JedisUtils.convertJedisAccessException(JedisUtils.java:72)atorg.springframework.data.redis.connection.jedis.JedisConnection.convertJedisAccessException(JedisConnection.java:135)atorg.springframework.data.redis.connection.jedis.JedisConnection.incrBy(JedisConnection.java:1099)atsun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethod)...RedisTemplate本身没有提供不需要序列化就可以存储的方法,有什么办法可以解决呢?
解决方案
解决方案二:
save方法,序列化是自己实现的:publicvoidsave(finalKredisKey,finalVdata){if(redisKey!=null&&data!=null){redisTemplate.execute(newRedisCallback<V>(){publicVdoInRedis(RedisConnectionconnection)throwsDataAccessException{byte[]bkey=ObjectTranscoder.serialize(redisKey);connection.set(bkey,ObjectTranscoder.serialize(data));connection.close();returnnull;}});}}incrBy方法:publicvoidincr(finalKredisKey,finallongincreValue){if(redisKey!=null){redisTemplate.execute(newRedisCallback<V>(){publicVdoInRedis(RedisConnectionconnection)throwsDataAccessException{byte[]bkey=ObjectTranscoder.serialize(redisKey);connection.incrBy(bkey,increValue);connection.close();returnnull;}});}}
解决方案三:
修改了一下,虽然功能是实现了,但是原子性没有了,并发时候会有问题,希望大神解决呀~publicvoidincr(finalKredisKey,finallongincreValue){if(redisKey!=null){redisTemplate.execute(newRedisCallback<V>(){publicVdoInRedis(RedisConnectionconnection)throwsDataAccessException{byte[]bkey=ObjectTranscoder.serialize(redisKey);Objectobj=ObjectTranscoder.deserialize(connection.get(bkey));if(obj==null){connection.close();returnnull;}longvalue=Long.valueOf(obj.toString())+increValue;longexpitedTime=connection.ttl(bkey);connection.setEx(bkey,expitedTime,ObjectTranscoder.serialize(value));connection.close();returnnull;}});}}谢谢。
解决方案四:
JedisConnectioncon=this.jedisConnectionFactory.getConnection();con.incr("a:a".getBytes());
这样试试看