@Override protected void doSubscribe(Node node, NotifyListener listener) { List<NodeType> listenNodeTypes = node.getListenNodeTypes(); if (CollectionUtils.isEmpty(listenNodeTypes)) { return; } for (NodeType listenNodeType : listenNodeTypes) { String listenNodePath = NodeRegistryUtils.getNodeTypePath(clusterName, listenNodeType); Notifier notifier = notifiers.get(listenNodePath); if (notifier == null) { Notifier newNotifier = new Notifier(listenNodePath); notifiers.putIfAbsent(listenNodePath, newNotifier); notifier = notifiers.get(listenNodePath); if (notifier == newNotifier) { notifier.start(); } } boolean success = false; NodeRegistryException exception = null; for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) { JedisPool jedisPool = entry.getValue(); try { Jedis jedis = jedisPool.getResource(); try { doNotify( jedis, Collections.singletonList(listenNodePath), Collections.singletonList(listener)); success = true; break; // 只需读一个服务器的数据 } finally { jedis.close(); } } catch (Throwable t) { exception = new NodeRegistryException( "Failed to unregister node to redis registry. registry: " + entry.getKey() + ", node: " + node + ", cause: " + t.getMessage(), t); } } if (exception != null) { if (success) { LOGGER.warn(exception.getMessage(), exception); } else { throw exception; } } } }
@Override protected void doRegister(Node node) { String key = NodeRegistryUtils.getNodeTypePath(clusterName, node.getNodeType()); String expire = String.valueOf(SystemClock.now() + expirePeriod); boolean success = false; NodeRegistryException exception = null; for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) { JedisPool jedisPool = entry.getValue(); try { Jedis jedis = jedisPool.getResource(); try { jedis.hset(key, node.toFullString(), expire); jedis.publish(key, Constants.REGISTER); success = true; if (!replicate) { break; // 如果服务器端已同步数据,只需写入单台机器 } } finally { jedis.close(); } } catch (Throwable t) { exception = new NodeRegistryException( "Failed to register node to redis registry. registry: " + entry.getKey() + ", node: " + node + ", cause: " + t.getMessage(), t); } } if (exception != null) { if (success) { LOGGER.warn(exception.getMessage(), exception); } else { throw exception; } } }