您不能使用 Ehcache 来执行此操作,因为缓存管理器按名称维护缓存,并且每个名称只能有一个缓存。您将需要使用另一个不强制使用唯一名称或不使用名称作为缓存管理器中的“键”的缓存实现。
编辑:这种方法有效,但不使用工厂 bean:
import java.util.concurrent.atomic.AtomicInteger
import net.sf.ehcache.Cache
import net.sf.ehcache.CacheManager
import net.sf.ehcache.store.MemoryStoreEvictionPolicy
import org.springframework.beans.factory.DisposableBean
import org.springframework.beans.factory.InitializingBean
class MyService implements InitializingBean, DisposableBean {
private static AtomicInteger counter = new AtomicInteger()
private Cache cache
private String cacheName
static scope = 'session'
void afterPropertiesSet() {
int maxElementsInMemory = 10000
int maxElementsOnDisk = 10000000
MemoryStoreEvictionPolicy memoryStoreEvictionPolicy = MemoryStoreEvictionPolicy.LRU
boolean overflowToDisk = true
boolean eternal = false
int timeToLive = 5000 // 120
int timeToIdle = 5000 // 120
boolean diskPersistent = false
int diskExpiryThreadIntervalSeconds = 120
int diskSpoolBufferSize = 0
cacheName = 'myservice-cache-' + counter.incrementAndGet()
cache = new Cache(cacheName, maxElementsInMemory, memoryStoreEvictionPolicy,
overflowToDisk, null, eternal, timeToLive, timeToIdle,
diskPersistent, diskExpiryThreadIntervalSeconds, null,
null, maxElementsOnDisk, diskSpoolBufferSize)
CacheManager.getInstance().addCache cache
}
void destroy() {
cache.removeAll()
CacheManager.getInstance().removeCache(cacheName)
}
}
由于服务是会话范围的,因此缓存不必是会话范围的,因为它完全由服务控制。通过实现InitializingBean
,您可以在会话开始时创建缓存,并在会话结束时通过实现将其删除DisposableBean
。随意使用不同的缓存名称方法;这只是保证它们是独一无二的。此外,我还根据默认值枚举了缓存构造函数值,EhCacheFactoryBean
但可以内联。