Spring redis cache is a high availability solution when redis is not available

Time:2020-7-29

problem

The spring redis cache is used online. When redis is unavailable, the interface will be unavailable and the page will report an error

solve

When redis is not available, call the method to query the database to obtain data

Modify rediscacheconfig

public class RedisCacheConfig extends CachingConfigurerSupport implements CachingConfigurer {
    @Override
    public CacheErrorHandler errorHandler() {
        return new CacheErrorHandler() {
            @Override
            public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
                log.error("Get: {} from cache failed", key, exception);
            }

            @Override
            public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {

            }

            @Override
            public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {

            }

            @Override
            public void handleCacheClearError(RuntimeException exception, Cache cache) {

            }
        };
    }

Just record the error log, and then continue to call the method. The page will return normally

@Cacheable(key = "'layout_'+#itemType+ '_pid_' + #itemPid",value = "layout")
public List<LayoutItemVO> getLayoutByPidAndType(String itemPid, Integer itemType)

Note: the default time-out of redis is one minute. The timeout can be set as small as 5S

spring.redis.timeout: 5000

Suppose the method takes 1s, and 6S will be returned when redis is not available

optimization

If redis can’t recover for a while, it can also disable cache dropping, that is, not caching
You can directly set the timeout to 0

Reference documents

https://dzone.com/articles/sa…