将整个表加载到缓存Grails中

pie*_*erk 1 grails hibernate grails-orm

可以在Grails启动时将整个表加载到缓存中吗?

例如,我有一个2个表,每个表有5000条记录,用作静态只读数据.这个数据是最受欢迎的,因为其他表的所有信息都是从这个只读表中派生出来的.

我知道grails有一个缓存使用场景,但是这个信息会在很短的时间后不断从缓存中逐出,并且只会在下一个请求中重新缓存.

基本上是通过不必访问此静态数据的数据库来减少响应时间.

谢谢

Bur*_*ith 6

您可以使用ehcache.xml配置缓存行为.如果您没有缓存,则使用默认值配置缓存,但如果您使用默认值,则使用默认值.把它放入grails-app/conf,它将被复制到类路径.

假设您的域类是com.yourcompany.yourapp.YourDomainClass,您可以指定要缓存的元素数量并设置eternal = true,这样它们就不会被丢弃:

<ehcache>

   <diskStore path='java.io.tmpdir' />

   <defaultCache
      maxElementsInMemory='10000'
      eternal='false'
      timeToIdleSeconds='120'
      timeToLiveSeconds='120'
      overflowToDisk='true'
      maxElementsOnDisk='10000000'
      diskPersistent='false'
      diskExpiryThreadIntervalSeconds='120'
      memoryStoreEvictionPolicy='LRU'
   />

   <cache name='com.yourcompany.yourapp.YourDomainClass'
      maxElementsInMemory='10000'
      eternal='true'
      overflowToDisk='false'
   />

   <!-- hibernate stuff -->
   <cache name='org.hibernate.cache.StandardQueryCache'
      maxElementsInMemory='50'
      eternal='false'
      timeToLiveSeconds='120'
      maxElementsOnDisk='0'
   />

   <cache
      name='org.hibernate.cache.UpdateTimestampsCache'
      maxElementsInMemory='5000'
      eternal='true'
      maxElementsOnDisk='0'
   />

</ehcache>
Run Code Online (Sandbox Code Playgroud)

有关如何配置的更多信息,ehcache.xml请参阅注释中包含大量文档的http://ehcache.org/ehcache.xml.

完成后,你BootStrap.groovy应该看起来像这样:

import com.yourcompany.yourapp.YourDomainClass

class BootStrap {

   def init = { servletContext ->
      def ids = YourDomainClass.executeQuery('select id from YourDomainClass')
      for (id in ids) {
         YourDomainClass.get(id)
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

调用get()每个实例后,将来的调用get()将使用二级缓存.