春季启动可缓存 -

问题描述:

我使用@Cacheable注释缓存我的方法的结果缓存空值。出于性能原因,我想缓存null和从方法返回的非空值。春季启动可缓存 -

但这里的问题是春天缓存非空值,但由于某些原因不缓存为空。

这里是我的代码:

@Cacheable(
      cacheManager = "promoCacheManager", 
      value = "promos:campaign", 
      key = "'promos:campaign:'.concat(#currencyId)" 
    ) 
    public PromosDto getPromosByCurrency(Integer currencyId) { 

... 

我已经尝试每一件事情。即使我设置

unless = "#result != null || #result == null"

但是这并没有很好的帮助。 任何指针?

检查您的高速缓存管理器的设置。

例如:RedisCacheManager有一个重载构造函数,您可以在其中指定cacheNullValues;这在默认情况下是错误的 - 尝试将其设置为true。

https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/cache/RedisCacheManager.html#RedisCacheManager-org.springframework.data.redis.core.RedisOperations-java.util.Collection-boolean-

还要记住:

注意当启用cacheNullValues请务必RedisOperations使用的RedisSerializer能够序列化NullValue属性的。

为什么不回Optional<PromosDto>安全地包裹空。这应该缓存罚款然后,根据https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/htmlsingle/#cache-annotations-cacheable-condition

+0

不是为我工作。还是一样。只有在可选内部的对象不为空时它才会缓存。 – Tariq

+0

您的缓存提供程序是否支持缓存空值? – Richard

+0

是的,我正在使用Redis缓存。所以它确实支持空值 – Tariq