【问题标题】:Load entire table into cache Grails将整个表加载到缓存 Grails
【发布时间】:2011-05-04 20:28:28
【问题描述】:

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

例如,我有 2 个表,每个表有 5000 条记录,用作静态只读数据。不过,此数据受到的打击最大,因为其他表上的所有信息都来自此只读表。

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

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

谢谢

【问题讨论】:

    标签: hibernate grails grails-orm


    【解决方案1】:

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

    假设您的域类是 com.yourcompany.yourapp.YourDomainClass,您可以指定要缓存的元素数量并设置永恒 = 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>
    

    有关如何配置ehcache.xml 的更多信息,请参阅http://ehcache.org/ehcache.xml,它在 cmets 中有很多文档。

    完成后,您的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)
          }
       }
    }
    

    已经为每个实例调用了get(),以后对get() 的调用将使用二级缓存。

    【讨论】:

    • Bootstrap.groovy 中的代码可以替换为YourDomainClass.list() 吗?
    猜你喜欢
    • 2016-07-26
    • 1970-01-01
    • 2018-11-23
    • 2012-03-31
    • 2019-12-13
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 2014-12-15
    相关资源
    最近更新 更多