0

I had configured Spring Boot + Ehcache3 to cache i18n messages pulled from the database and everything was working fine until I expanded and encountered null results from the database for some keys. Ehcache barfed with a ClassCaseException saying the default org.springframework.cache.support.NullValue is not the expected com.example.Message. After wrestling with this, I tried a dual cache arrangement. One the DAO impl:

@Caching(cacheable = {
    @Cacheable(value = "messages", key = "#locale + ':' + #key", unless = "#result == null"),
    @Cacheable(value = "nullMessages", key = "#locale + ':' + #key", unless = "#result != null")})
public Optional<Message> findByKeyAndLocale(String key, String locale) {
   // fun with JDBC
}

and in the ehcache.xml:

    <cache alias="messages" uses-template="default"  >
        <key-type>java.lang.String</key-type>
        <value-type>com.example.Message</value-type>
    </cache>
    <cache alias="nullMessages" uses-template="default" >
        <key-type>java.lang.String</key-type>
        <value-type>org.springframework.cache.support.NullValue</value-type>
    </cache>

This seems to be working OK. My question here is: Is there a better way? The two caches are using the same key, but it looks like that key is potentially computed twice. Is there a way to improved that? Better yet, is there a magic incantation to enable ehcache3 to handle null result caching out-of-the-box?

-GBS

Jeebus
  • 35
  • 4
  • Duplicate of: https://stackoverflow.com/questions/43607684/how-to-cache-null-values-with-ehcache-3 ? – moilejter Mar 14 '22 at 22:22
  • Saw that post, but I am not doing explicit puts and gets; Spring Boot is running the caching via annotations. Also, if I specify the cache's value type in `ehcache.xml` as the general `Serializable` rather than `Message` or `NullValue`, it balks about the both of those types. If I specify `Message`, `NullValue` won't work and vice versa. Hence the use of two different caches and why I am asking for feedback on this particular scenario. – Jeebus Mar 15 '22 at 00:37

0 Answers0