我想使用 Spring 缓存 @Cacheable 来管理缓存。 而真正的缓存是redis。
我的代码是这样的:
@PostMapping("/post")
@CachePut(value = "abc", key = "#key")
public String putInRedis(@RequestParam String key, @RequestParam String value) {
saveInDB(key, value);
return value;
}
@GetMapping("/get")
@Cacheable(value = "abc", key = "#key")
public String queryRedis(@RequestParam String key) {
return findByKey(key);
}
在我收到发布请求后
localhost:8080/post?key=key&value=value
redis服务器出现一个奇怪的key
127.0.0.1:6379> keys *
1) "abc:\xac\xed\x00\x05t\x00\x03key"
127.0.0.1:6379> GET "abc:\xac\xed\x00\x05t\x00\x03key"
"\xac\xed\x00\x05t\x00\x05value"
weird-redis-key-with-spring-data-jedis
@Cacheable的Serializer如何设置成默认的StringRedisTemplate:
public StringRedisTemplate() {
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
setKeySerializer(stringSerializer);
setValueSerializer(stringSerializer);
setHashKeySerializer(stringSerializer);
setHashValueSerializer(stringSerializer);
}
我的应用程序.properties:
spring.redis.host=localhost
spring.redis.password=
spring.redis.port=6379
构建.gradle
group 'io.freezhan'
version '1.0-SNAPSHOT'
buildscript {
repositories {
maven {
url 'https://plugins.gradle.org/m2/'
}
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE'
}
}
task wrapper(type: Wrapper) {
gradleVersion = '2.13'
distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip"
}
apply plugin: 'java'
apply plugin: 'spring-boot'
sourceCompatibility = 1.5
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
compile("org.springframework.boot:spring-boot-starter-data-redis")
compile("org.springframework.boot:spring-boot-starter-jetty")
compile("org.springframework.boot:spring-boot-starter-actuator")
compile 'org.projectlombok:lombok:1.16.10'
testCompile("junit:junit")
}
最佳答案
创建一个redis模板
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;
}
为什么它会创建一个奇怪的字符串作为键?
key 是根据您的方法中存在的参数属性创建的,该方法被注释为可缓存。 spring就是这样从redis中读取缓存值的。
关于java - spring boot缓存redis,key有\xac\xed\x00\x05t\x00\x06,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39324717/