The Redis cache data used in Spring can be directly manipulated via redistemplate or @cacheable annotations (as described in another article: Spring cachable key definition and application). Regardless of the method used, the key, value is serialized into a byte array, or a string is saved. Redistemplate source code can be seen, its serialization is through a series of Redisserializer interface implementation.
Hashkey-hashvalue,key-value, respectively, corresponding to the hash structure and the non-hash structure of the serialization mechanism, so we can separately set the key, value of the serialization mechanism, but also for the hash and non-hash to distinguish processing. If none of these are specified, Redistemplate chooses the Defaultserializer configuration to serialize.
The default implementation of Defaultserializer is Jdkserializationredisserializer, a typical problem with this serialization is that objects defined for generics are saved in binary format, which is not the least efficient in serialization, But the length will be more than the tail, affecting readability and transmission efficiency, like this:
The improvement method is simple, replacing the default serialization interface implementation mechanism, using Jackson2jsonredisserializer, or Kryoredisserializer, or custom implementations. The following is an example of the Jackson implementation:
@Beanpublic redistemplate redistemplate (jedisconnectionfactory connectionfactory) {Redistemplate RedisTemplate = n EW redistemplate (); Redistemplate.setconnectionfactory (ConnectionFactory); Replace the default serialization Jackson2jsonredisserializer Jackson2jsonredisserializer = new Jackson2JsonR using Jackson2jsonredisserialize Edisserializer (Object.class); Objectmapper objectmapper = new Objectmapper (); Objectmapper.setvisibility (Propertyaccessor.all, JsonAutoDetect.Visibility.ANY); Objectmapper.enabledefaulttyping (ObjectMapper.DefaultTyping.NON_FINAL); Jackson2jsonredisserializer.setobjectmapper (Objectmapper); Sets the serialization rule for value and the serialization rule for key Redistemplate.setvalueserializer (Jackson2jsonredisserializer); Redistemplate.sethashvalueserializer (Jackson2jsonredisserializer); Redistemplate.setkeyserializer (New Stringredisserializer ()); Redistemplate.sethashkeyserializer (Redistemplate.getkeyserializer ()); Redistemplate.afteRpropertiesset (); return redistemplate;} Now, the results of the cache will look like this:
Regarding the performance aspect, the interest can own test, the Kryoredisserializer compression rate and the speed is optimal, Fastjson second, the default is the worst.
Spring Data Redis Serialization