I am using @Cacheable annotation to cache the results of my method. For performance reason I want to cache both null and non-null values returned from method.
But problem here is Spring is caching non-null values but not caching null for some reason.
Here is my code:
@Cacheable(
cacheManager = "promoCacheManager",
value = "promos:campaign",
key = "'promos:campaign:'.concat(#currencyId)"
)
public PromosDto getPromosByCurrency(Integer currencyId) {
...
I have tried every thing. Even I set
unless = "#result != null || #result == null"
But that didn't help as well. Any pointer on this?
Check your cache manager settings.
For example: RedisCacheManager has an overloaded constructor where you can specify cacheNullValues; this is false by default - try setting it to 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-
Also keep in mind:
NOTE When enabling cacheNullValues please make sure the RedisSerializer used by RedisOperations is capable of serializing NullValue.
Why not return Optional<PromosDto> to safely wrap a null. That should cache fine then, according to https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/htmlsingle/#cache-annotations-cacheable-condition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With