缓存不起作用 - Ehcache + Spring注释

时间:2012-10-11 10:03:10

标签: spring jdbc ehcache spring-annotations

我是Ehcache的新手。我尝试了一个Spring和Ehcache的例子。 缓存似乎不起作用。当我尝试调试时,服务层返回对象但它没有被缓存。缓存中的键为空。

以下是我的代码:

的web.xml

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml, /WEB-INF/cache-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

缓存-config.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    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">

    <ehcache:annotation-driven cache-manager="cacheManager" />
    <bean id="cacheManager"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
        p:config-location="/WEB-INF/ehcache-config.xml" p:shared="true"/>
</beans>

ehcache的-config.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">
    <defaultCache eternal="true" maxElementsInMemory="100"
        overflowToDisk="false" />
    <cache name="userCache" maxElementsInMemory="100" eternal="true"
        overflowToDisk="false" />   
</ehcache>

控制器:

@RequestMapping(value = "/test.htm")    
    public void getUsers() {


        loginService.getUser();

        Cache userCache = this.cacheManager.getCache("userCache");

        List<String> userCacheKey = userCache.getKeys();        

    }

ServiceImpl:

@Override
@Cacheable(cacheName="userCache")   
public User getUser() { 

    String SQLUSERByName = "SELECT * FROM User where user_id=1000";
    User user= getJdbcTemplate().queryForObject(SQLUSERByName, new UserMapper());   
    return user;

}

我使用的是Spring 3.1版本。

0 个答案:

没有答案