Search code examples
cachinggrailsredis

Grails Redis Cache - Calling @Cacheable annoted method indirectly - how to work


I have the following case in grails 2.5.3:

EmployeeService{

    @Cacheable(value = "employees")
    public List<Employee> getEmployeeList() {
        return Employee.list()
    }

    public Employee getEmployee(long id){
        return getEmployeeList().find{it.id == id}
    }
}



EmployeeController{

    def employeeService

    def getEmployee(long id){
        render employeeService.getEmployee(id) as JSON
    }
}

My problem is - the @Cacheable annotated method in EmployeeService does not store data in Redis cache, what should I do to accomplish exactly this case.

Thank you in advance.


Solution

  • The caching is provided by spring. So you need to use the spring way to call methods to apply the caching:

    EmployeeService {
        def grailsApplication
    
        @Cacheable(value = "employees")
        public List<Employee> getEmployeeList() {
            return Employee.list()
        }
    
        public Employee getEmployee(long id){
            return proxy.getEmployeeList().find {it.id == id}
        }
    
        // using springs bean proxy ensures cacheable aspects are applied
        private getProxy() {
            grailsApplication.mainContext.employeeService
        }
    }