Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Cacheable - Cache null values

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?

like image 251
Tariq Avatar asked Oct 27 '25 09:10

Tariq


2 Answers

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.

like image 157
Lamak Qaizar Avatar answered Oct 28 '25 22:10

Lamak Qaizar


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

like image 44
Richard Avatar answered Oct 28 '25 23:10

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!