Spring boot caching with redis,key have \xac\xed\x00\x05t\x00\x06
Create a redis template
private RedisTemplate<String, ?> createRedisTemplateForEntity() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(getRedisConnectionFactory());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
Why is it creating a weird string as key?
The key is created based on the argument attributes present in your method which is annotated as cacheable. This is how spring reads the cache value from redis.
The caching - feature of Spring allows to use different cache - implementations. One of them is Redis. It can be used with the class RedisCacheManager
. The Spring documentation says:
If Redis is available and configured, the
RedisCacheManager
is auto-configured.
This is the approach that I propose to influence the Redis - caching - integration:
Define the
RedisCacheManager
as bean on your own.Pass the
RedisTemplate
to the constructor ofRedisCacheManager
.
I found an example for this on the Internet using a programmmatic configuration. There is also an example using XML-based configuration.
like mm759's answer:
Define the RedisCacheManager as bean on your own.
- Pass the RedisTemplate to the constructor of RedisCacheManager.
this code will solve my problem:
package io;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Created by freezhan on 16/9/5.
*/
@Configuration
public class CacheConfig {
@Autowired
private StringRedisTemplate redisTemplate;
@Bean
public CacheManager cacheManager() {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
return cacheManager;
}
}
and the redis store like this: