Gre*_*Lei 2 java spring ehcache
我一直在使用Spring Cache Abstraction和ehcache。我在目标方法上使用@Cacheable注解,如下所示:
@Component
public class DataService {
@Cacheable(value="movieFindCache", key="#name")
public String findByDirector(String name) {
return "hello";
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的jUnit测试:
public class ServiceTest extends AbstractJUnit4SpringContextTests{
@Resource
private DataService dataService;
@Test
public void test_service() {
System.err.println(dataService.findByDirector("Hello"));
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用jUnit test调试时,这不能正常工作。它引发一个IllegalArgumentException,如下所示:
java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?) CacheableOperation[public java.lang.String com.eliteams.quick4j.web.service.ExcelDataService.getCarData()] caches=[movieFindCache] | key='#name' | condition='' | unless=''
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.cache.interceptor.CacheAspectSupport.generateKey(CacheAspectSupport.java:315)
at org.springframework.cache.interceptor.CacheAspectSupport.collectPutRequests(CacheAspectSupport.java:265)
Run Code Online (Sandbox Code Playgroud)
我有以下配置:
applicationContext.xml:
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:ehcache.xml" p:shared="true"/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="ehCacheManagerFactory"/>
Run Code Online (Sandbox Code Playgroud)
ehcache.xml:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<cache name="movieFindCache"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="1000"
eternal="false"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="300" timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap" />
</cache>
Run Code Online (Sandbox Code Playgroud)
注意:如果我未在@Cacheable批注中指定“键”,它将起作用。
有什么我忘记指定的吗?配置?注释?
小智 7
您可以尝试将密钥替换为#p0
@Component
public class DataService {
@Cacheable(value="movieFindCache", key="#p0")
public String findByDirector(String name) {
return "hello";
}
}
Run Code Online (Sandbox Code Playgroud)
Spring Cache Abstraction VS接口VS密钥参数的引用 (“为缓存操作返回了空密钥”错误)
有同样的问题,根本原因是在测试参数真的为空,所以,只是添加了非空检查
@Cacheable(value="movieFindCache", key="#p0", condition="#p0!=null")
public String findByDirector(String name) {...}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13769 次 |
| 最近记录: |