可以在Grails启动时将整个表加载到缓存中吗?
例如,我有2个表,每个表有5000条记录,这些表用作静态只读数据。但是,此数据受到的打击最大,因为其他表上的所有信息均来自该只读表。
我知道grails有一个缓存使用情况,但是此信息在短时间后会不断从缓存中清除,并且它仅在下一个请求时才被重新缓存。
基本上是通过不必访问此静态数据的数据库来尝试减少响应时间。
谢谢
最佳答案
您可以使用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>
有关如何配置
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)
}
}
}
在为每个实例调用了
get()
之后,以后对get()
的调用将使用第二级缓存。
关于hibernate - 将整个表加载到缓存Grails中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5889455/