问题描述
@cacheable方法始终执行并传入timetoLiveSeconds
cache-service.xml
<?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: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 create-missing-caches="true" cache-manager="cacheManager" />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerfactorybean">
<property name="shared" value="true" />
</bean>
<bean id="cacheKeyGenerator" class="com.test.StringArgumentCacheKeyGenerator" />
</beans>
pom.xml
<properties>
<jdk.version>1.8</jdk.version>
<spring.framework.version>5.1.6.RELEASE</spring.framework.version>
<spring.security.version>3.2.9.RELEASE</spring.security.version>
<spring.integration.version>5.1.4.RELEASE</spring.integration.version>
</properties>
<dependency>
<groupId>com.googlecode.ehcache-spring-annotations</groupId>
<artifactId>ehcache-spring-annotations</artifactId>
<version>1.1.3</version>
</dependency>
ehcache.xml
<cache name="myList"
overflowTodisk="false" statistics="true"
eternal="false"
maxElementsInMemory="10000"
timetoIdleSeconds="0"
timetoLiveSeconds="300"
memoryStoreevictionPolicy="LFU" />
java类:每当我访问显示部门的页面时,都会调用getDepartmentsList()。 我将系统添加到“我正在获取部门”进行调试。 timetoLiveSeconds设置为5分钟。因此,我希望如果能在5分钟内刷新页面,就不会看到打印语句“我正在得到部门”。
public class MyClass
{
@Cacheable(cacheName = "myList",keyGeneratorName = "cacheKeyGenerator" )
public final Map<String,String> getDepartmentsList(String userid) {
System.out.println("I am getting the dept");
Map<String,String> deptMap = myService.getAuthorizedDept(userid);
return deptMap;
}
}
我是Spring ehcache的新手,调试这并不容易。我能够通过添加system.out来解决此问题的唯一方法。对于解决此问题的任何帮助/建议,我将不胜感激。谢谢
public class MyClass
{
public final Map<String,String> getDepartmentsList(String userid) {
System.out.println("I am getting the dept" );
Map<String,String> deptMap = myService.getAuthorizedDept(userid);
return deptMap;
}
}
@Service
public class Myservice
{
@Cacheable(cacheName = "myList",keyGeneratorName = "cacheKeyGenerator" )
public Map<String,String> getDepartmentsList(String userid){
}
}
基于上面的内容,它在2分钟内刷新了
- 我要去的部门是2020/09/30 20:10:56
- 我要去的部门是2020/09/30 20:12:57
基于上面的内容,它在2分钟内刷新,但时间设置为5分钟(timetoLiveSeconds =“ 300”)
谢谢大家到目前为止的评论。
解决方法
首先,您应该使用@Component或@Service将MyClass设置为Bean。 然后,在另一个spring对象(例如Controller或RestController)中调用方法getDepartmentsList()。如果在同一类中调用该方法,则缓存将无效。