Spring redis cache 当redis不可用的时候的高可用的一种解决方案
文章目录
问题
线上使用的是spring redis cache, 当redis不可用会导致接口也不可用 页面报错
解决
当redis不可用的时候 去调用方法查询数据库获取数据
修改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) {
}
};
}
仅记录一下错误日志 然后会继续调用方法 页面会有正常的返回
@Cacheable(key = "'layout_'+#itemType+ '_pid_' + #itemPid",value = "layout")
public List<LayoutItemVO> getLayoutByPidAndType(String itemPid, Integer itemType)
注意:默认redis超时时间是一分钟 超时时间可以设小点 如5s
spring.redis.timeout: 5000
假设方法用时1s 当redis不可用的时候 6s会有返回
优化
如果redis一时半会恢复不了 也可以整个的禁止掉缓存 即不走缓存了
可以直接将超时时间设为0
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论