【发布时间】:2021-01-21 12:35:06
【问题描述】:
我正在使用Spring Boot 2.4.2 和
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在我的应用中,我有
package com.tuto.app1;
import lombok.Data;
@Data
public class Student {
private String firstName;
private String lastName;
private int age;
}
还有
@Bean
public CacheManager redisCacheManager() {
RedisSerializationContext.SerializationPair<Object> jsonSerializer =
RedisSerializationContext.SerializationPair.fromSerializer(new new Jackson2JsonRedisSerializer<>(Object.class));
return RedisCacheManager.RedisCacheManagerBuilder
.fromConnectionFactory(redisConnectionFactory())
.cacheDefaults(
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofDays(1))
.serializeValuesWith(jsonSerializer)
)
.build();
}
和
@GetMapping("/students/{name}")
@Cacheable(value = "student")
public Student getStudent(@PathVariable String name) {
Student student = new Student();
student.setFirstName("John");
student.setLastName(name);
student.setAge(30);
return student;
}
第一次调用http://.../app1/students/toto 返回
{
"firstName": "John",
"lastName": "toto",
"age": 30
}
在缓存中我有
{"firstName":"John","lastName":"toto","age":30}
好的,这就是我想要的。
但是......所有其他对http://.../app1/students/toto的呼叫都在给我
class java.util.LinkedHashMap cannot be cast to class com.tuto.app1.Student (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; com.tuto.app1.Student is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @32bd421)
java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class com.tuto.app1.Student (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; com.tuto.app1.Student is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @32bd421)
解决办法是什么?
【问题讨论】:
-
这就是我正在做的,只是它使用了 GenericJackson2JsonRedisSerializer。这样做的 cahe 包含 {"@class":"com.tuto.app1.Student","firstName":"John","lastName":"toto","age":30}。好的,它正在醒来。即使是第二次通话。但这不是我想要的。我想保留没有类名的json。
标签: spring-boot spring-data-redis