Today I share a question about RedisTemplate. If you are interested, you can continue to read it. If you are not interested, you can continue to flirt with women.

A friend gave me a picture with an error, why can’t I get the value?

My first reaction was whether RedisTemplate and StringRedisTemplate would use two different connections so that one Key could be found and the other Key could not be found.

After repeated confirmation, the Connection is ok, is the same, or the same sentence: every strange problem must have a story behind it.

Can only debug source bai, what else to do. Finally in the redis. Clients. Jedis. BinaryJedis# hget found problems, is no return at all in redis data.

Now the question remains why does a StringRedisTemplate query return data, but a RedisTemplate query does not?

Let’s take a look at the relationship between StringRedisTemplate and RedisTemplate, StringRedisTemplate inherits from RedisTemplate, which is specialized for string manipulation.

RedisTemplate is usually used for more complex object operations, depending on the serialization.

So I used the Redis client to look at the format of the stored data and found that the Hash format was a string.

And that’s why you can get it with StringRedisTemplate, which is the StringRedisTemplate you use when you’re estimating storage.

The default serialization of RedisTemplate is JDK serialization, in the wrong format.

Therefore, I checked the construction mode of RedisTemplate and found that the serialization mode was inconsistent.

So will be changed to stringSerializer jdkSerializationRedisSerializer. Ran the test again and it still didn’t work. So I looked at the information of the RedisTemplate object as follows:

ValueSerializer has been changed, but hash is serialized in JDK.

Let’s change them all to the same, as follows:

In my opinion, this is still a problem of use. Maybe everyone thinks that the two redistemplates are the same and there is no difference, which leads to the problems in this paper.

If you are careful enough, in fact, look at the source code will know the difference between these two classes.

StringRedisTemplate is built with all serializations set to String by default, meaning that StringRedisTemplate’s data format is String.

RedisTemplate is JDK if it’s not set.

If you are interested, you can pay attention to my wechat public number, Simtiandi, and read more technical articles for the first time. I also have some open source code on GitHub github.com/yinjihuan