首页 文章

带有ehcache的Spring 3.1 @Cacheable不起作用

提问于
浏览
1

我的带有Spring和ehcache的@Cacheable不起作用,没有数据放在缓存上 . 当应用程序调用可缓存方法getFolProfile时,数据库始终是调用而不是缓存 . 请问,我可以告诉我我的代码中有什么问题 .

我的root-context.xml:

<cache:annotation-driven proxy-target-class="true"/>   
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:/cache/ehcache.xml"  /> 
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehcache"/>

我的服务:

import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;

    @Service
    public class FolManager {
@Autowired
FolDao folDao;



@Cacheable(value = "oneCache", key = "#email")
public FolProfileForm getFolProfile(String email) {
    return folDao.retrieveByLogin(email);
}
    }

我的ehcache.xml:

<?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <diskStore path="c:/tmp" />
    <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120"
    timeToLiveSeconds="120" overflowToDisk="true" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
    diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />
    <cache name="oneCache" maxElementsInMemory="100000" maxElementsOnDisk="10000000" eternal="true" diskPersistent="true"
    overflowToDisk="true" diskSpoolBufferSizeMB="20" memoryStoreEvictionPolicy="LFU" />
    </ehcache>

谢谢你的帮助Michel

4 回答

  • 0

    看起来您正在服务层中定义缓存 . 在http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html,具体注意如下:

    注意<cache:annotation-driven />仅查找在其定义的同一应用程序上下文中的bean上的@ Cacheable / @ CacheEvict . 这意味着,如果您将<cache:annotation-driven />放在WebApplicationContext中DispatcherServlet,它只检查控制器中的@ Cacheable / @ CacheEvict bean,而不检查您的服务 . 有关更多信息,请参见第16.2节“DispatcherServlet” .

  • 0

    加上这个

    <cache:annotation-driven cache-manager="cacheManager"  />
    

    你必须告诉Spring缓存管理器在哪里 .

  • 2

    当proxy-target-class属性设置为true时,将创建基于类的代理 . CGLIB将用于为给定的目标对象创建代理 . 在您的依赖项中创建CGlIB .

    如果您可以选择,则通过将proxy-target-class属性设置为false并在类上实现至少一个接口来选择JDK动态代理 .

  • 0

    请检查您的ehCache日志,查看以下异常:

    java.io.NotSerializableException: com.googlecode.ehcache.annotations.RefreshableCacheEntry
    

    您使用磁盘持久性缓存(diskPersistent = true),因此您必须检查FolProfileForm对象是否可序列化 . 从ehCache文档:

    只有Serializable的数据可以放在DiskStore中 . 使用ObjectInputStream和Java序列化机制写入磁盘和从磁盘写入 . 将删除溢出到磁盘存储区的任何非可序列化数据,并抛出NotSerializableException .

    可能是您的数据未放置到缓存(文件系统)的情况,因此它会尝试一次又一次地从方法调用中获取它 . 您可以使用内存存储缓存,甚至可以保存不可序列化的数据 .

相关问题