public GroupYedis(GroupConfig groupConfig) { this.groupConfig = groupConfig; msHolder.master = new Yedis(groupConfig.getMasterAtomConfig()); msHolder.slaves = createYedis(groupConfig.getSlaveAtomConfigs()); msHolder.loadBalancer = createLoadBalancer(msHolder.slaves, groupConfig.getLoadBalancerType()); this.groupConfig.addListener(this); }
@Override public synchronized void onChanged(MasterSlaveConfigManager configManager) { // 如果已经关闭,则忽略配置变更 if (shutdown.get()) { return; } MsHolder newMsHolder = new MsHolder(); Yedis unusedMaster = null; List<Yedis> unusedSlaves = null; try { // 处理master的变化 try { AtomConfig masterConfig = groupConfig.getMasterAtomConfig(); if (!msHolder.master.getConfig().getServerInfo().equals(masterConfig.getServerInfo())) { newMsHolder.master = new Yedis(groupConfig.getMasterAtomConfig()); logger.info( "Master changed to " + groupConfig.getMasterAtomConfig().getHost() + ":" + groupConfig.getMasterAtomConfig().getPort()); unusedMaster = msHolder.master; } else { newMsHolder.master = msHolder.master; } } catch (Exception e) { // 如果有异常,则需要关闭刚才新建的实例 unusedMaster = newMsHolder.master; throw e; } // 处理slave的变化:构造slaves,从已有yedis中复用,最后,没被复用的则close List<Yedis> createdSlaves = new ArrayList<Yedis>(); try { List<AtomConfig> slaveConfigs = groupConfig.getSlaveAtomConfigs(); if (slaveConfigs != null) { List<Yedis> oldSlaves = new ArrayList<Yedis>(msHolder.slaves); List<Yedis> newSlaves = new ArrayList<Yedis>(slaveConfigs.size()); for (AtomConfig config : slaveConfigs) { Yedis existsYedis = takeSlaveIfExists(oldSlaves, config.getServerInfo()); if (existsYedis != null) { // 复用已经存在的Yedis newSlaves.add(existsYedis); } else { // 是新的server,则构建Yedis Yedis yedis = new Yedis(config); newSlaves.add(yedis); createdSlaves.add(yedis); logger.info( "New slave created: " + yedis.getConfig().getHost() + ":" + yedis.getConfig().getPort()); } } newMsHolder.loadBalancer = createLoadBalancer(newSlaves, groupConfig.getLoadBalancerType()); newMsHolder.slaves = newSlaves; unusedSlaves = oldSlaves; } } catch (Exception e) { // 如果有异常,则需要关闭刚才新建的实例 unusedSlaves = createdSlaves; throw e; } // 切换 this.msHolder = newMsHolder; } catch (Exception e) { logger.error( "Master/slave Config changed, but error occurred, so GroupYedis haven't switched connection: ", e); } // 释放无用的yedis if (unusedMaster != null) { unusedMaster.close(); logger.info( "Unused master closed: " + unusedMaster.getConfig().getHost() + ":" + unusedMaster.getConfig().getPort()); } if (unusedSlaves != null) { for (Yedis yedis : unusedSlaves) { yedis.close(); logger.info( "Unused slave closed: " + yedis.getConfig().getHost() + ":" + yedis.getConfig().getPort()); } } }