Jedis主从切换实现

1.redis配置文件

配置文件示例:
127.0.0.1:6379|127.0.0.1:6380|127.0.0.1:6381|127.0.0.1:6382|127.0.0.1:6383
这里,对每一行的配置会以“|”分隔。最前面的redis会作为主节点。后面的redis会作为最前面一台的备份Jedis,存放在bakRedisMap(Map)中。


2.主备切换流程

先访问主的jedis,如果抛出JedisConnectionException,则catch中将会逐次ping其备份的jedis,如果存在work的从Redis(通过ping来确定),则返回对应的jedis实例,否则向外抛JedisConnectionException。
具体代码:
	/**
	 * 从备份Redis群中取出可用的Jedis,如果均失败,则抛出异常。底层采用ping
	 * 
	 * @param bakjedisArray
	 * @param index
	 * @return
	 */
	private final Jedis getWorkBakJedis(Jedis curJedis, Jedis[] bakjedisArray, int index) {
		if (index == 0) {
			System.out.println(getJedisUniqueName(curJedis) + " JedisConnectionException!");
			bakjedisArray = redisConfig.getBakRedisMap().get(getJedisUniqueName(curJedis));
			if (bakjedisArray == null) {
				throw new JedisConnectionException(getJedisUniqueName(curJedis) + "  No BakRedis!");
			}
		}
		Jedis bakjedis = bakjedisArray[index];
		try {
			bakjedis.ping();
			return bakjedis;
		} catch (JedisConnectionException e) {
			System.out.println(getJedisUniqueName(bakjedis) + " JedisConnectionException!");
			if (index == bakjedisArray.length - 1) {// 当前节点是最后的节点,直接抛出异常
				throw new JedisConnectionException(
						getJedisUniqueName(curJedis) + "  All bak Jedis ConnectionException!");
			} else {
				return getWorkBakJedis(curJedis, bakjedisArray, index + 1);
			}
		}
	}


你可能感兴趣的:(Jedis主从切换实现)