【问题标题】:@Cacheable annotation cannot work as expected when deserialize beans with LocalDateTime type property当反序列化具有 LocalDateTime 类型属性的 bean 时,@Cacheable 注释无法按预期工作
【发布时间】:2022-08-06 20:47:01
【问题描述】:

我发现当方法返回一个Java Bean类型时注解@Cacheable不能工作,这是完整的描述:

  1. 我在一个使用spring缓存的方法上注释了@Cacheable:
    @Cacheable(cacheNames=\"userCache\", key=\"#userId\")
    public User getUser(long userId){
        return userRepository.getUserById(userId);
    }
    

    像这样的用户类:

    public class User{
        Long userId;
        String username;
        @JsonSerialize(using = LocalDateTimeSerializer.class)
        @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")
        private LocalDateTime birthDateTime;
    }
    

    如您所见,我注释了相关的 Jackson 注释以使 LocalDateTime 类型的 Jackson 反序列化工作,这是 pom.xml 中的相关依赖项:

            <dependency>
                <groupId>com.fasterxml.jackson.datatype</groupId>
                <artifactId>jackson-datatype-jsr310</artifactId>
                <version>2.12.5</version>
            </dependency>
    
    1. 之后,我像这样调用@Cacheable 方法getUser:
    User user = userCache.getUser(1L);
    

    并引发异常:

    org.redisson.client.RedisException:处理命令时出现意外异常在 org.redisson.command.CommandAsyncService.convertException(CommandAsyncService.java:326) 在 org.redisson.command.CommandAsyncService.get(CommandAsyncService.java:123) 在 org.redisson.RedissonObject.get(RedissonObject.java:82) ...废话引起:com.fasterxml.jackson.databind.exc.InvalidDefinitionException:Java 8 日期/时间类型java.time.LocalDateTime 默认不支持:添加模块 \"com.fasterxml.jackson.datatype:jackson-datatype-jsr310\" 以启用处理在 [来源:(io.netty.buffer.ByteBufInputStream);行:1,列:101](通过引用链:com.stackoverflow.domain.User[\"birthDateTime\"])在 com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67) 在 com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1764) 在 com.fasterxml.jackson.databind.deser.impl.UnsupportedTypeDeserializer.deserialize(UnsupportedTypeDeserializer.java:36) 在 com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)

    3.在我使用@Cacheable之前,直接从数据库中获取用户是没有问题的。但是当我开始使用@Cacheable 时,它​​总是抛出上面的异常,无论我是否为LocalDateTime 配置了那些Jackson 反序列化。 @Cacheable 是否不能与具有 LocalDateTime 属性的 Java Bean 一起使用,或者只是我对 Jackson 的配置是错误的?

  • 顺便说一下,CacheManager是Redis,如异常所示
  • 欢迎来到堆栈溢出。从消息来看,问题似乎与不包括 javatime 模块的 redisson 配置有关,这似乎通过您可以在 spring 项目中反序列化 LocalDateTime 而没有问题的事实得到证实。我不知道redis,但我认为您必须检查是否可以将javatimemodule 添加到其配置中。
  • 感谢您的评论,我会检查它
  • 正确的,Spring\'s 缓存抽象(例如,当使用 @Cacheable 注释时)不处理任何形式的进出缓存提供程序的缓存条目的序列化。这是所有缓存提供程序配置特定的。 Spring 缓存只是“信使”。

标签: jackson spring-cache localdatetime jsr310


【解决方案1】:

我有同样的问题。 Spring Cache 不使用其他 Spring 组件使用的隐式 ObjectMapper。

  1. 包含模块,您已经这样做了。
  2. 创建一个将覆盖默认 Spring Cache 配置的配置:
    @Configuration
    @EnableCaching
    public class CacheConfiguration {
        @Bean
        public RedisSerializationContext.SerializationPair<Object> serializationPair() {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.registerModule(new JavaTimeModule())
                .activateDefaultTyping(
                    objectMapper.getPolymorphicTypeValidator(),
                    ObjectMapper.DefaultTyping.EVERYTHING,
                    JsonTypeInfo.As.PROPERTY
                );
            return RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
        }
    
        @Bean
        public RedisCacheConfiguration redisCacheConfiguration(
            @Value("${cache.default-ttl-in-seconds}") Integer ttl,
            RedisSerializationContext.SerializationPair<Object> serializationPair
        ) {
            return RedisCacheConfiguration.defaultCacheConfig()
                .disableCachingNullValues()
                .entryTtl(Duration.ofSeconds(ttl))
                .serializeValuesWith(serializationPair);
        }
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-05
    • 2019-12-18
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    相关资源
    最近更新 更多