简体   繁体   中英

Caching domain objects in Grails

I have been considering implementing EhCache in my Grails domain objects like this :

static mapping = {
   cache true
}

I am not too familiar with exactly how this caching mechanism works and was wondering what a good rule of thumb is in determining which domain objects would benefit from being cached. eg, objects that are accessed rarely.. often... ?

Thanks!

Caching only works for get() calls by default, but queries use the query cache if you update them with cache: true (criteria and HQL).

cache true creates a read-write cache but you can configure a read-only cache with

static mapping = {
   cache usage:'read-only'
}

The read-only cache is good for lookup data that never changes, for example states, countries, roles, etc.

If you have domain classes that update, create, or delete frequently, query caching will often be slower than not caching. This is because changes like these cause all cached queries to be cleared, so you're often going directly to the database anyway. See http://tech.puredanger.com/2009/07/10/hibernate-query-cache/ for a more detailed description of this. For this reason I rarely use query caching and often disable it completely with

hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=false
    cache.provider_class='org.hibernate.cache.EhCacheProvider'
}

Domain classes that are "read-mostly" are the best candidates for read-write caching. The caches get cleared for each update, create, and delete, but if these are somewhat rare you'll see an overall performance boost.

Hibernate has an API to monitor cache usage. The http://grails.org/plugin/app-info and http://grails.org/plugin/hibernate-stats plugins make the information available and you can use the approach there in your own code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM