项目使用 spring+springMVC+mybatis+redis 框架,redis 实现了mybatis 的二级缓存,Jedis 客户端。
现在的问题是,一旦在运行中redis 挂掉,比如我手动把它停掉,整个使用缓存的查询都用不了了,因为jedis会报 JedisConnectionException,是一种 RuntimeException。
那有没有方法让 redis server 连接失败时,通知mybatis 去db 查询,而不是死磕redis 呢?相当于让项目直接绕过redis 进行工作。
苦恼,有没有做过的前辈给指点指点,感激不尽!

解决方案 »

  1.   

    我也想知道redis挂了怎么保持正常
      

  2.   

    在进行redis 查询前   调用 ping 命令 得到有效响应 进行查询,不行就执行 数据库语句
      

  3.   


    道理是如此,问题是如何通知mybatis,mybatis 只能处理cache 为null,为{} 空,不知道怎样用代码手动控制其去查询 db
      

  4.   

    这就是典型的容灾处理,
    咱们可以尝试从程序设计的角度开始,
            1.抽象 缓存管理对象 CacheManager  set(),get(),
            2.项目中的缓存实现  RedisCacheImpl,本地也有缓存,LocalCacheImpl ,等等。
            3.CacheFacade 包含一个测试redis连通性的方法,注入CacheManager 对象,
               伪代码:
        public class CacheFacade {
               private CacheManager  cache;
               //获取缓存代码实现
               public Object  get(){
               }
               //
               public boolean testCache(){
               }
        }
    利用好java的aop。对方法进行有效切割,达到预期效果。
            
      

  5.   

    正常设计都是先查redis ,redis没查到数据,再去查数据库,之后缓存到redis。  挂了也没问题啊
      

  6.   

    封装好redis操作, 有异常 catch好 记好日志,做好报警, 遇到异常和查不到数据 然后执行查库
      

  7.   

    给你参考一下我的RedisHelper读取缓存的代码:
    /**
     * 获取缓存,不存在时调用方法进行填充
     * @param key 缓存key
     * @param cacheSecond 缓存时长,单位秒
     * @param fillWhileNoFound 缓存不存在时的数据获取方法,用于填充缓存
     * @param <T> 缓存数据类型
     * @return 缓存数据
     * @throws Exception 方法的异常
     */
    public static<T> T getCache(String key, int cacheSecond, Callable fillWhileNoFound) throws Exception {
        Object ret = redis.opsForValue().get(key);
        if (ret != null)
            return (T) ret;
        try {
            ret = fillWhileNoFound.call();
            if (ret == null) {
                return null;
            }
        }catch (Exception exp){
            log.error(exp.toString());
        }
        redis.opsForValue().set(key, ret, Duration.ofSeconds(cacheSecond));
        return (T) ret;
    }