当前位置: 首页 > 知识库问答 >
问题:

Spring Boot Data Redis——序列化为json->class java。util。无法强制转换LinkedHashMap

夏理
2023-03-14

我使用的是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;
}

第一次调用超文本传输协议://...

{
"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)

解决办法是什么?


共有1个答案

申嘉慕
2023-03-14

您可以为redis设置json字符串数据。例如:

redistemplate.opsxxx.set("key",JSON.toJsonString(new JavaBean()));
String json = redistemplate.opsxxx.get("key");
//convert
JSON.parseObject(json,JavaBean.class);
 类似资料: