spring-boot - Spring Redis 缓存中的 ClassCastException

标签 spring-boot redis spring-data spring-cache redis-cache

我正在使用 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

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

Caused by: java.lang.ClassCastException: com.cryptocurrency.exchange.sample.model.SampleRecord cannot be cast to com.cryptocurrency.exchange.sample.model.SampleRecord

这个异常的原因是什么?

最佳答案

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

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

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

关于spring-boot - Spring Redis 缓存中的 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59638203/

相关文章:

java - 如何仅使用关联对象的外键来保存 Spring 实体

ruby-on-rails - 如何在 redis rails 中订阅多个发布者?

Redis-Sentinel with Redis 其CONFIG命令被重命名

java - spring boot ResourceLoader遍历jar包中的文件

java - @PersistenceContext 不适用于参数。如何通过构造函数注入(inject)EntityManager?

java - 如何在 Controller 中将 RequestBody 定义为列表,我收到 500 错误

node.js - 对 Node.js 日志记录系统进行基准测试——我是否遗漏了一些相关信息?

java - 如何使@CreatedBy和@CreatedDate在Spring数据jdbc中不可修改?

java - 一对多映射不起作用 Spring data JPA

Spring,Spring Data JPA : org. hibernate.hql.internal.ast.QuerySyntaxException:测试未映射