From Hell To Heaven: Safeguarding your application – Part 1

Have you ever wondered how to safeguard your application when using the database and a cache like Redis? What if one of them is down? What should we do? These are questions that every developer should ask themselves when building an API that needs to be reliable 24/7.

In this guide, we will be configuring a cache error handler that will cover every scenario where Spring Cache annotations are used.

Building the cache error handler

The reason to build a custom error handler is simple: we want the application working even though the cache is down.

We will need to do two things: Implement the CacheErrorHandler interface and registering into our application. Below is the implementation of our class:

package com.jerieshandal.api.config; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.Cache; import org.springframework.cache.interceptor.CacheErrorHandler; @Slf4j public class CustomCacheErrorHandler implements CacheErrorHandler { @Override public void handleCacheGetError(RuntimeException e, Cache cache, Object o) { log.error(e.getMessage(), e); } @Override public void handleCachePutError(RuntimeException e, Cache cache, Object o, Object o1) { log.error(e.getMessage(), e); } @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object o) { log.error(e.getMessage(), e); } @Override public void handleCacheClearError(RuntimeException e, Cache cache) { log.error(e.getMessage(), e); } } Read more...