15.2.3.3. Caching the Result of a Method Invocation
A common practice for time or resource intensive operations is to save the results in a cache for future access. The following code is an example of such an operation:
A common approach is to cache the results of this method call and to check the cache when the result is next required. The following is an example of a code snippet that looks up the result of such an operation in a cache. If the results are not found, the code snippet runs the
toCelsiusFormatted method again and stores the result in the cache.
In such cases, the Infinispan CDI module can be used to eliminate all the extra code in the related examples. Annotate the method with the
@CacheResult annotation from the javax.cache.annotation package instead, as follows:
Due to the annotation, Infinispan checks the cache and if the results are not found, it invokes the
toCelsiusFormatted() method call.
Note
The Infinispan CDI module allows checking the cache for saved results, but this approach should be carefully considered before application. If the results of the call should always be fresh data, or if the cache reading requires a remote network lookup or deserialization from a cache loader, checking the cache before call method invocation can be counter productive.
15.2.3.3.1. Specify the Cache Used Copy linkLink copied to clipboard!
Copy linkLink copied to clipboard!
Add the following optional attribute (
cacheName) to the @CacheResult annotation to specify the cache to check for results of the method call:
@CacheResult(cacheName = "mySpecialCache")
public void doSomething(String parameter) {
...
}
@CacheResult(cacheName = "mySpecialCache")
public void doSomething(String parameter) {
...
}