/** * 判断两个node对象中host和port是否相等 * * @author ningyu * @date 2013-1-26 下午3:46:50 * @param anObject * @return * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof Node) { Node node = (Node) anObject; if (this.getHost().equals(node.getHost()) && (this.getPort() == node.getPort())) { return true; } } return false; }
/** * 执行redis ping操作 * * @author ningyu * @date 2013-1-26 下午3:51:07 * @param node * @return * @see */ public static boolean pingNode(Node node) { Jedis j = null; try { j = new Jedis(node.getHost(), node.getPort()); String re = j.ping(); return re.equals("PONG"); } catch (Exception e) { return false; } finally { if (j != null) { j.disconnect(); } } }
/** * 将字符串描述转换成node对象 * * @author ningyu * @date 2013-1-26 下午3:47:28 * @param msg * @return * @see */ public static Node unmarshal(String msg) { Node head = null; Node node = null; String str = msg.substring(1, msg.length() - 1); String[] nodes = str.split("\\},\\{"); for (String s : nodes) { String[] ps = s.split(","); Node cur = new Node(); cur.setHost(ps[0].split(":")[1]); cur.setPort(Integer.valueOf(ps[1].split(":")[1])); String password = ps[2].split(":")[1]; cur.setPassword(password.equals("null") ? null : password); cur.setWeight(Integer.valueOf(ps[3].split(":")[1])); String name = ps[4].split(":")[1]; cur.setName(name.equals("null") ? null : name); String timeout = ps[5].split(":")[1]; if (timeout.endsWith("}")) { timeout = timeout.substring(0, timeout.length() - 1); } cur.setTimeout(Integer.valueOf(timeout)); if (node == null) { node = cur; head = node; } else { node.setNext(cur); cur.setPrevious(node); node = cur; } } return head; }
/** * 返回json字符串 * * @author ningyu * @date 2013-1-26 下午3:47:45 * @param node * @return * @see */ private static String passJson(Node node) { StringBuilder sb = new StringBuilder(); if (node != null) { sb.append("{"); sb.append("host:" + node.getHost()).append(", "); sb.append("port:" + node.getPort()).append(", "); sb.append("password:"******", "); sb.append("weight:" + node.getWeight()).append(", "); sb.append("name:" + node.getName()).append(", "); sb.append("timeout:" + node.getTimeout()); sb.append("}"); node = node.getNext(); if (node != null) { sb.append(","); sb.append(passJson(node)); } } return sb.toString(); }