【发布时间】:2023-03-27 13:21:01
【问题描述】:
我正在尝试设置一个 EHCache,它将用于在同一 Tomcat 实例上运行的各种 WAR 文件。
我正在缓存的对象是自定义 Java bean。我正在使用 EHCache 版本 2.8.3
理想情况下,我希望只在 Tomcat 通用类加载器上共享 ehcache JAR,据我所知,这应该是可能的。
我正在做的测试有两个 Web 服务,ServiceA 和 ServiceB,它们使用相同的缓存,因为 EHCache JAR 位于 Tomcat 公共库文件夹中。
当我向 ServiceA 发出请求时,结果对象成功插入到缓存中。
当我向 ServiceB 发出相同请求时,结果对象已成功从缓存中检索。
但是,当我返回到 ServiceA 并发出请求时,它会抛出 ClassCastException
<faultcode>S:Server</faultcode>
<faultstring>com.company.platform.auth.user.AuthenticatedUser cannot be cast to com.company.platform.auth.user.AuthenticatedUser</faultstring>
EHCache 文档建议我应该将 copyOnRead 属性设置为 true 以确保缓存始终使用序列化。但是,添加它似乎对我不起作用
http://terracotta.org/documentation/3.7.4/enterprise-ehcache/configuration-guide#copy-on-read
缓存配置:
<cache name="myCache"
maxElementsInMemory="2000"
copyOnRead="true"
copyOnWrite="true"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="0"
timeToLiveSeconds="3600"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off"
/>
使用方法上的 Spring @Cacheable 注解管理缓存数据:
@Cacheable(
value=CACHE_NAME,
key="#username + ':' + T(com.company.platform.auth.handlers.EncryptionHandler).encrypt(#password)",
unless="#result == null")
public AuthenticatedUser authenticate(String username, String password) {
【问题讨论】:
-
您好,这应该可以按预期工作。您能否添加您所看到的异常的堆栈跟踪以及围绕放入和从缓存中获取的代码的 sn-ps?
-
@LouisJacomet 目前我通过在发送到缓存之前自己处理序列化来修复它。但是,这不是理想的解决方案,如果 ehcache 可以自己处理它会更好。我没有例外,但没有太多例外,它在 $Proxy 类上失败并且在堆栈中没有显示任何细节。但是,我将添加我与缓存交互的方式(它是通过 spring
@Cacheable注释)