Spring Redis缓存中的ClassCastException

我正在使用Spring Boot版本2.1.8.RELEASE开发Spring Boot应用程序。 我需要构建自定义的RedisCacheManager。

RedisCacheManager如下。

@EnableCaching
@Configuration
class CacheConfig {
    @Bean
    fun redisCacheManager(lettuceConnectionFactory: RedisConnectionFactory): RedisCacheManager? {
        val redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(1))

        return RedisCacheManager.RedisCacheManagerBuilder
            .fromConnectionFactory(lettuceConnectionFactory)
            .cacheDefaults(redisCacheConfiguration)
            .build()
    }
}

在我的服务中,我使用@Cacheble缓存响应。参见:

@Cacheable(cacheNames = ["cached_sample"])
    fun getallSample(): List<SampleRecord> {
        return auditableRepository.findAll()
    }

我缓存的模型:

data class SampleRecord(
    @ApiModelProperty(readOnly = true)
    val id: Long? = null,@ApiModelProperty(readOnly = true)
    val active: Boolean? = null,@ApiModelProperty(readOnly = true)
    val createdDate: Instant? = null,val param: String
): Serializable

第二次调用函数时,出现以下异常

原因:java.lang.ClassCastException:com.cryptocurrency.exchange.sample.model.SampleRecord无法转换为com.cryptocurrency.exchange.sample.model.SampleRecord

该异常的原因是谁?

qq125486395 回答:Spring Redis缓存中的ClassCastException

如果您在依赖关系树中使用Spring开发工具,则会发生此问题。有一个相当简单的解决方案,但是没有很好地记录下来。反序列化对象时,需要设置Redis缓存配置以引用Context类加载器。对于您的代码,它看起来像:

redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
 .entryTtl(Duration.ofHours(1))
 .defaultCacheConfig(Thread.currentThread().getContextClassLoader())

.defaultCacheConfig(Thread.currentThread()。getContextClassLoader())确保反序列化时Redis引用了Context类加载器。 Spring在此处的“已知问题”部分中对此进行了概述:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-devtools-known-restart-limitations

本文链接:https://www.f2er.com/2807369.html

大家都在问