【问题标题】:Spring Boot Data Redis - Serialize to json -> class java.util.LinkedHashMap cannot be castSpring Boot Data Redis - 序列化为 json -> 类 java.util.LinkedHashMap 无法强制转换
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 2020-07-09
    • 2018-08-08
    • 2022-01-20
    • 1970-01-01
    • 2017-07-21
    • 2018-10-06
    • 1970-01-01
    • 2018-06-10
    相关资源
    最近更新 更多