二级缓存不能与Spring和JSF一起工作



我使用Hibernate4+Spring4.0.3.RELEASE+JSF2.0+hibernate-ehcache4.1.0Final为我的web应用程序,我已经在我的项目中实现了二级缓存,但它不工作这里是代码

applicationContext.xml file (Inside WEB-INF folder)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:sec="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <ehcache:annotation-driven />
    <ehcache:config cache-manager="cacheManager">
        <ehcache:evict-expired-elements
            interval="60" />
    </ehcache:config>
    <bean id="cacheManager"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="/WEB-INF/ehcache.xml" />
    </bean>
    <context:component-scan base-package="com.ccc.spring" />
    <context:annotation-config />
    <context:spring-configured />

    <!-- Data Source Declaration -->
    <bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test" />
        <property name="user" value="user" />
        <property name="password" value="password" />
        <property name="maxPoolSize" value="2" />
        <property name="maxStatements" value="0" />
        <property name="minPoolSize" value="1" />

    </bean>

    <!-- Session Factory Declaration -->
    <bean id="SessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="DataSource" />
        <property name="packagesToScan"> <list> <value>com.ccc.spring.model</value> 
            </list> </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
                </prop>

                <!--useful for debugging -->
                <prop key="hibernate.generate_statistics">true</prop>
            </props>
        </property>
        <!-- <property name="loadTimeWeaver"> <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" 
            /> </property> <property name="persistenceUnitName" value="danielme_persistenceunit" 
            /> -->
    </bean>
    <!-- Enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="txManager" />
    <!-- Transaction Manager is defined -->
    <bean id="txManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="SessionFactory" />
    </bean>
</beans>

ehcache.xml file(Inside WEB-INF folder)

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <defaultCache maxElementsInMemory="100" eternal="false"
        timeToIdleSeconds="120" timeToLiveSeconds="20000" />
    <cache name="ValidUserRole" maxElementsInMemory="100"
        eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="20000" />

在DAO文件中,我使用以下代码

 @Cacheable( value = "ValidUserRole" )
    public List<Validuserrole> getRoleList() {
        List list = null;
        try{
          list = getSessionFactory().getCurrentSession()
                .createQuery("from Validuserrole ").list();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }

但是当我调试代码时,它每次都从DB获取数据,而不是从二级缓存

你混合了两种不同的东西hibernate二级缓存和spring缓存支持,这是两种不同的东西。你在试着把两者混合起来。更糟糕的是,您正在尝试使用Spring-Ehcache,它基本上是spring自己的缓存支持的前身。

缓存方法结果

对于初学者来说,删除spring-ehcache的东西,切换到spring提供的缓存支持。这将使@Cacheable注释工作。如果这就是您想要的,那么就不用二级缓存了。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"      
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    http://www.springframework.org/schema/cache
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:sec="http://www.springframework.org/schema/security"
    xsi:schemaLocation="
                 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                 http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
                 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                 http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <constructor-arg ref="ehcacheManager" />
</bean>
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="/WEB-INF/ehcache.xml" />
</bean>

注意:也建议使用无版本的xsd文件,这样你就可以确保你总是使用属于你的Spring版本的模式文件。

二级缓存

对于二级缓存工作,你必须了解它是如何工作的,首先你的实体必须是可缓存的,如果不是这样的话,什么都不会被缓存。

@Entity
@Cacheable // Note this is from hibernate NOT spring!!!
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Validuserrole { ... }

接下来,查询将被执行,但是结果对象(当可缓存时)将保存在内存中。然后,下一次需要同一实体实例时,将返回缓存中的实例。

查询缓存

如果你想启用查询缓存,你必须使查询可缓存,否则它不会被缓存。

list = getSessionFactory().getCurrentSession()
            .createQuery("from Validuserrole ")
            .setCacheable(true)
            .list();

最新更新