Caching service methods

Openmrs-core uses Spring Cache combined with Ehcache to provide ability for caching services.

The config for ehCache is loaded form ehcache-api.xml file, but you can extend it by creating apiCacheConfig.properies file.

Annotating service methods

Spring comes with several caching annotations, that you can use on your service methods. Basic annotation are @Cachable and @CacheEvict.  
Annotating your method with @Cachable tells spring to cache the data when calling the method for the first time. When this method will be called again Sping will use cached data instead of taking it form the database. This will make your application more efficient.  
The basic usage of this annotation could look like this:

@Cacheable(value = "userSearchLocales")
public List<Locale> getSearchLocales(Locale currentLocale, User user) throws APIException {...}

When the getSearchLocales() method will be called the returned data will be cached and associated with the cache name "userSearchLocales".
Ok, this is all great but what if the data will be changed? We don't want to get outdated data. This is why we need to use another annotation @CacheEvict. It should be used on methods where the data might be changed e.g.:

@CacheEvict(value = "userSearchLocales", allEntries = true)
public GlobalProperty saveGlobalProperty(GlobalProperty gp) {...}

Once we call saveGlobalProperty() method all entries associated with "userSearchLocales" will be deleted from cache.
For more information go to the Spring docs.

Extending cache configuration by modules

Cache configuration is loaded from ehcache-api.xml file, but you can extend this by creating apiCacheConfig.properies file in your module's resource directory. It can contains multiple cache configurations and as long as they are not set in ehcache-api.xml they will be applied.
Example file:


As you can see there are two cache configs: "userSearchLocales" and "subscription". The format of one line should look like {cacheName}.{property}={value}. All available properties for ehcache configuration can be found here