【问题标题】:Spring with ehcache not caching objects带有ehcache的Spring不缓存对象
【发布时间】:2015-05-16 21:14:48
【问题描述】:

我正在使用带有 ehcache 的 spring 4.1。我可以使用整数键缓存字符串值,但是每当我尝试缓存对象时,它都会失败而没有任何错误。我保存在缓存中的模型(POJO)确实实现了 hashcode、equals 和 tostring 函数。

ehcache配置如下

<diskStore path="E:/ymserviceslog" />

<defaultCache maxElementsInMemory="50" eternal="false"
overflowToDisk="false" memoryStoreEvictionPolicy="LFU" />

<cache name="test" maxElementsInMemory="1000" eternal="false"
overflowToDisk="true" memoryStoreEvictionPolicy="LRU"
timeToLiveSeconds="3000" diskPersistent="true" />

Spring配置如下

<cache:annotation-driven proxy-target-class="true"/>
<context:component-scan base-package="com.ashitosh.ym.dao" />

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
            <property name="cacheManager" ref="ehcache" />
</bean>

<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml" />
    <property name="shared" value="true"/>
</bean>

<bean id="cachedao" class="com.ashitosh.ym.dao.Cache"/>

我要缓存的类和方法

public class Cache implements Icache {

    @Override
    @Cacheable(value = "test", key="#id")
    public Party getPerson(int id) {
        Party party = new Party("data",1);
        return party;
    }

}

如果我将方法 getPerson 的返回值从 Party 对象替换为 String,它就可以工作。 有什么想法吗?

【问题讨论】:

  • 你的问题很模糊。你在使用 JCache + Spring 集成吗?您的缓存配置如何?在有人愿意帮助你之前,你真的需要改进它。
  • 嗨 R4J,我已经修改了我的问题。希望我现在清楚了。
  • “它没有任何错误就失败了”:你能更具体一点吗?你得到一个例外但没有明确的根本原因?你从来没有打过缓存?还是??
  • 嗨,Louis,对象没有被缓存。另外,我在日志中没有任何异常。

标签: spring ehcache


【解决方案1】:

我解决了! 我需要为需要缓存的对象类实现可序列化。

public class Party implements Serializable {

    private static final long serialVersionUID = 1L;

...

【讨论】:

  • 我也面临同样的问题。我也为我的缓存对象类实现了 Serializable。它仍然没有缓存。你还做了其他改变吗?
  • @Rache,请检查复杂对象的哈希码和 equals 方法。这就讲了这两个foreach.be/blog/spring-cache-annotations-some-tips-tricks的重要性
  • @Rache 我需要做的是确保类的所有属性也是可序列化的,如果它们是自定义类的话。