1

我想在 grails 服务中使用一个 ehcache 会话范围。

我设法在 config/resources.groovy 中有一个来自这个定义的缓存 bean

myCache(org.springframework.cache.ehcache.EhCacheFactoryBean) {
      timeToIdle = 5000 // life span in seconds
      timeToLive = 5000 // life span in seconds
      }

但是从工厂获得的对象是单例范围的。

在会话范围的服务中拥有会话范围的 ehcache 的最佳方法是什么?

谢谢

4

1 回答 1

2

您不能使用 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但可以内联。

于 2012-12-04T16:03:53.583 回答