Spring boot 从redis读取我自己的对象时出现序列化异常
我在Spring Boot中使用以下配置:Spring boot 从redis读取我自己的对象时出现序列化异常,spring-boot,kotlin,redis,jackson,Spring Boot,Kotlin,Redis,Jackson,我在Spring Boot中使用以下配置: @Bean fun defaultRedisCacheConfiguration(): RedisCacheConfiguration { return RedisCacheConfiguration .defaultCacheConfig() .prefixKeysWith(keyPrefix) .serializeValuesWith(jsonSerializer()) .en
@Bean
fun defaultRedisCacheConfiguration(): RedisCacheConfiguration {
return RedisCacheConfiguration
.defaultCacheConfig()
.prefixKeysWith(keyPrefix)
.serializeValuesWith(jsonSerializer())
.entryTtl(Duration.ofSeconds(0))
}
@Bean
override fun cacheManager(): CacheManager {
val objectMapper =
ObjectMapper()
.registerModule(KotlinModule())
.registerModule(JavaTimeModule())
.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY)
objectMapper.registerSubtypes(Check::class.java)
val cacheNamesConfigurationMap = Caches.values().associate {
it.cacheId to RedisCacheConfiguration
.defaultCacheConfig()
.prefixKeysWith(keyPrefix)
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(GenericJackson2JsonRedisSerializer(objectMapper))
)
.entryTtl(Duration.ofSeconds(it.timeToLiveInSeconds))
}
return RedisCacheManager(redisCacheWriter(), defaultRedisCacheConfiguration(), cacheNamesConfigurationMap)
}
通过这种配置,我想在redis中存储和读取一个简单的kotlin数据对象。对象的数据类如下所示:
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
data class Check(
@JsonProperty("a")
var a: List<String> = listOf(""),
): Serializable
运行代码时,会收到以下错误消息:
2021-04-30 10:59:52.645 [XNIO-1 task-6] level=WARN o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolved [org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Missing type id when trying to resolve subtype of [simple type, class java.lang.Object]: missing type id property '@class'
at [Source: (byte[])"{"type":"Check","a":["java.util.Collections$SingletonList",["test"]]}"; line: 1, column: 69]; nested exception is com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class java.lang.Object]: missing type id property '@class'
at [Source: (byte[])"{"type":"Check","a":["java.util.Collections$SingletonList",["test"]]}"; line: 1, column: 69]]
最后,我的目标是使用@cacable注释来存储我自己的数据对象。奇怪的是,当我在列表中写入自己的数据对象时,缓存会工作,例如:
cacheManager.getCache("check")?.put("result", listOf(Check(listOf("test"))))
cacheManager.getCache("check")?.put("result", listOf(Check(listOf("test"))))