使用 EhCache3 在 Spring Boot 中缓存 null

发布于 2025-01-14 06:30:18 字数 1190 浏览 3 评论 0原文

我已经配置了 Spring Boot + Ehcache3 来缓存从数据库中提取的 i18n 消息,一切都工作正常,直到我扩展并遇到数据库中某些键的空结果。 Ehcache 抛出 ClassCaseException 异常,表示默认的 org.springframework.cache.support.NullValue 不是预期的 com.example.Message 。经过一番思考后,我尝试了双缓存安排。其中一个 DAO 实现:

@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
}

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>

似乎工作正常。我的问题是:有更好的方法吗?两个缓存使用相同的密钥,但看起来该密钥可能被计算两次。有办法改善吗?更好的是,是否有一个神奇的咒语可以让 ehcache3 处理开箱即用的空结果缓存?

-GBS

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文