小编典典

使用Redis进行Spring Boot缓存,密钥为\ xac \ xed \ x00 \ x05t \ x00 \ x06

redis

我想使用Spring cache @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);
}

在我有职位要求后

本地主机: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"

spring缓存

如何设置@Cacheable的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")
}

阅读 530

收藏
2020-06-20

共1个答案

小编典典

Spring的缓存功能允许使用不同的缓存实现。Redis是其中之一。可以与class一起使用RedisCacheManager。在Spring文档说:

如果Redis可用并已配置,则将RedisCacheManager自动配置。

这是我建议影响Redis(缓存)集成的方法:

  1. RedisCacheManager自己定义as bean。

  2. 将传递RedisTemplate给的构造函数RedisCacheManager

我在Internet上使用编程配置找到了一个示例。还有一个使用基于XML的配置的示例

2020-06-20