title: Redis Cache in Spring with json : map key serialization
body: <p>Hope you can help me with this.</p>
  
  <p>I'm using spring-boot 1.3.0M5 with Redis as cache implementation ,via annotations.</p>
  
  <pre><code>    @Bean
  // redis template used for caching
  public RedisTemplate&lt;String, Object&gt; cacheRedisTemplate()    {
      RedisTemplate&lt;String, Object&gt; redisTemplate = new RedisTemplate();
      redisTemplate.setKeySerializer(new StringRedisSerializer());
      redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer());
      redisTemplate.setValueSerializer(jackson2JsonRedisSerializer());
      redisTemplate.setConnectionFactory(connectionFactory());
      return redisTemplate;
  }
  
  @Bean
  public Jackson2JsonRedisSerializer&lt;Object&gt; jackson2JsonRedisSerializer() {
      final Jackson2JsonRedisSerializer&lt;Object&gt; jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
      final ObjectMapper objectMapper = Jackson2ObjectMapperBuilder
              .json()
              .build();
      objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
      jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
      return jackson2JsonRedisSerializer;
  }
  </code></pre>
  
  <p>Then, i do have a @service class that retrieves some information from internet, and it's cached via @cacheable.</p>
  
  <pre><code> @Cacheable(value = "forecasts", key = "'forecasts'", cacheManager = "forecastCacheManager")
  public Map&lt;Integer, Forecast&gt; retrieveForecasts() {
    &lt; retrieve data &gt;
  
    return stream.collect(Collectors
      .&lt;Forecast, Integer, Forecast&gt;toMap(o -&gt; o.getGame(), o -&gt; o));
   }
  </code></pre>
  
  <p>Then, in my controller , i do execute </p>
  
  <pre><code>forecastMap.get(1)
  </code></pre>
  
  <p>which, at first time, works, but after redis caches it, the integer key is serialized as String, and then deserialized back as String, so it won't work again, as the key will be "1" instead of 1.</p>
  
  <p>I've tried using @JsonDeserialize(keyAs = Integer.class), and also trying to register an objectMapper module, but none works.</p>
  
  <p>Thanks a lot.</p>