HomeGuidesChangelog
GuidesGitHubLog In
Guides

Cache

Getting started with resilience4j-cache

Create and configure Cache

The following example shows how to decorate a lambda expression with a Cache abstraction. The cache abstraction puts the result of the lambda expression in a cache instance (JCache) and tries to retrieve a previous cached result from the cache before it invokes the lambda expression. If the cache retrieval from a distributed cache fails, the exception is taken care of and the lambda expression is called.

// Create a CacheContext by wrapping a JCache instance.
javax.cache.Cache<String, String> cacheInstance = Caching
  .getCache("cacheName", String.class, String.class);
Cache<String, String> cacheContext = Cache.of(cacheInstance);

// Decorate your call to BackendService.doSomething()
CheckedFunction1<String, String> cachedFunction = Decorators
    .ofCheckedSupplier(() -> backendService.doSomething())
    .withCache(cacheContext)
    .decorate();
String value = Try.of(() -> cachedFunction.apply("cacheKey")).get();

Consume emitted CacheEvents

The Cache emits a stream of CacheEvents. An event can be a cache hit, a cache miss or an error.

cacheContext.getEventPublisher()
    .onCacheHit(event -> logger.info(...))
    .onCacheMiss(event -> logger.info(...))
    .onError(event -> logger.info(...));

Ehcache example

compile 'org.ehcache:ehcache:3.7.1'
// Configure a cache (once)
this.cacheManager = Caching.getCachingProvider().getCacheManager();
this.cache = Cache.of(cacheManager
    .createCache("booksCache", new MutableConfiguration<>()));

// Get books using a cache
List<Book> books = Cache.decorateSupplier(cache, library::getBooks)
    .apply(BOOKS_CACHE_KEY);

❗️

It's not recommended to use JCache Reference Implementation in production since it causes some concurrency issues. Use Ehcache, Caffeine, Redisson, Hazelcast, Ignite or other implementation.