I have a site where users will first enter their search criteria. The search combines data from 2 sources, one of which is not a database. The search results are generally large enough to be paged.
Since the initial query is expensive, I would like to cache the search results if the search criteria doesn't change for subsequent page views.
My current method looks like:
def search(criteriaMap, offset, pagesize)
What is the best way of caching the search results in groovy/grails? How would I expire the search results?
Note, I see there is a springcache plugin but I am not sure if this will work for paged results. I also know that grails is packaged with ehcache but I haven't seen an API I directly have access to, I have only seen it used for 2nd level caching with GORM.
Update: I took part of @mfloryan's solution to solve this.
I created two methods in the searchService:
@Cacheable("searchCache")
def searchResults(uid, trimmedParams)
def trimParams(params)
(One is cached and the other is not.)
My code in the searchController:
def trimmedParams = searchService.trimParams(params)
def results = searchService.searchResults(trimmedParams)
//Page results
results = HelperService.pageResults(results, params.offset, params.max)
[results: results, searchParams : trimmedParams]
As a results, I invoked the search service with a trimmed list of parameters that do not include paging params. The cached search results can be returned.
The searchController takes care of the paging.
note: I didn't cache the hibernate results because I would end up with double the data in the cache. I only cached the combined results from searchService.searchResults (which hits a REST API and my local database)