我想使用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服务器看起来很奇怪
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);
}
我的application.properties:
spring.redis.host=localhost
spring.redis.password=
spring.redis.port=6379
的build.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")
}
3 回答
Spring的缓存 - 功能允许使用不同的缓存 - 实现 . 其中一个是Redis . 它可以与类
RedisCacheManager
一起使用 . Spring documentation说:这是我建议影响Redis的方法 - 缓存 - 集成:
自己定义
RedisCacheManager
作为bean .将
RedisTemplate
传递给RedisCacheManager
的构造函数 .我在Internet上使用programmmatic配置找到了example . 还有一个example使用基于XML的配置 .
像mm759的答案:
将RedisCacheManager定义为您自己的bean .
将RedisTemplate传递给RedisCacheManager的构造函数 .
这段代码将解决我的问题:
和redis商店这样:
创建一个redis模板
为什么它的创作是一个奇怪的关键?
密钥是根据方法中存在的参数属性创建的,该参数属性被注释为可缓存 . 这就是spring从redis读取缓存值的方式 .