Skip to content

Instantly share code, notes, and snippets.

@syhily
Last active November 6, 2015 15:29
Show Gist options
  • Select an option

  • Save syhily/38531c5cb9ffaaa3a9ad to your computer and use it in GitHub Desktop.

Select an option

Save syhily/38531c5cb9ffaaa3a9ad to your computer and use it in GitHub Desktop.
import com.google.common.collect.Maps;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import java.util.Map;
import java.util.ResourceBundle;
/**
* 类名称: ZkClientUtils <br>
* 类描述: A sync tool based on zkCli, inspired by sharp-config. (LOL)<br>
*
* @author yufan.sheng
* @version 1.0.0
* @since 15/8/10 上午8:27
*/
public class ZkClientUtils {
private static final ResourceBundle zkRb = ResourceBundle
.getBundle("runtimecfg/zkConfig");
private static final Logger logger = LoggerFactory
.getLogger(ZkClientUtils.class);
private static final Map<String, ZkListener> listenerMap = Maps.newHashMap();
/**
* Configure The ROOT Node
*/
private static final String ROOT_NODE = "/ROUTER";
private static ZkClient zkClient = null;
static {
init();
}
/**
* No More Objects
*/
private ZkClientUtils() {}
/**
* zkCli Lock Path Definition
*/
private static void createPath(String path) {
path += "/";
// Beautiful! Cool! Awesome!
for (int index = 1; (index = path.indexOf("/", index + 1)) != -1; ) {
String node = path.substring(0, index);
if (!zkClient.exists(node)) {
zkClient.createPersistent(node);
}
}
}
/**
* Init The Basic Configuration For zkCli
*/
private static void init() {
if (zkClient == null) {
try {
zkClient = new ZkClient(
zkRb.getString("zkServers").trim(),
Integer.parseInt(zkRb.getString("sessionTimeout").trim()),
Integer.parseInt(zkRb.getString("connectionTimeout").trim()));
} catch (Exception e) {
logger.error("init zookeeper fail", e);
}
} else {
logger.debug("zkCli is already initialized.");
}
}
/**
* Notify The Key Which Has been changed
*/
public static void updateConfig(String syncKey, Object syncData) {
String appNode = String.format("%s/%s", ROOT_NODE, syncKey);
createPath(appNode); // Create Sync Node On zookeeper
zkClient.writeData(appNode, syncData);
}
public static void addListener(String syncKey, ZkListener zkListener) {
String appNode = String.format("%s/%s", ROOT_NODE, syncKey);
createPath(appNode); // 创建应用节点
if (listenerMap.get(appNode) == null) {
listenerMap.put(appNode, zkListener);
zkClient.subscribeDataChanges(appNode, new IZkDataListener() {
@Override
public void handleDataDeleted(String path) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("appNode delete:{}", path);
}
}
@Override
public void handleDataChange(String path, Object value)
throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("appNode change:{}", path);
}
ZkListener listener = listenerMap.get(path);
if (listener != null) {
listener.update(value);
}
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment