使用 EhCache3 在 Spring Boot 中缓存 null
我已经配置了 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论