use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project java-apply by javachengwc.
the class CuratorWatch method watch.
/**
* 监听节点变化
*/
public static void watch() throws Exception {
PathChildrenCache cache = new PathChildrenCache(zkclient, "/zk", false);
cache.start();
System.out.println("监听开始/zk........");
PathChildrenCacheListener plis = new PathChildrenCacheListener() {
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
switch(event.getType()) {
case CHILD_ADDED:
{
System.out.println("Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
case CHILD_UPDATED:
{
System.out.println("Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
case CHILD_REMOVED:
{
System.out.println("Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
}
}
};
// 注册监听
cache.getListenable().addListener(plis);
// 一直会监听节点变化,而不像原始Watcher是一次性的
}
use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project blockchain by vincentbin.
the class RegistryCenter method registerService.
/**
* register server & observer active online server
* @param host local ip
* @param port local port
* @return 注册前是否有活跃线上机器
* @throws Exception zk watch
*/
public boolean registerService(String host, int port) throws Exception {
RegistryCenter.host = host;
RegistryCenter.port = port;
List<String> activeList = getServiceList();
try {
RegistryPackage registryPackage = new RegistryPackage();
registryPackage.setHost(RegistryCenter.host);
registryPackage.setPort(RegistryCenter.port);
String registryPackageJson = registryPackage.toJson();
byte[] bytes = registryPackageJson.getBytes();
String path = NameSpaceEnum.ZK_REGISTRY_PATH.getValue().concat("/node-") + registryPackage.hashCode();
path = this.zkClient.createPathData(path, bytes);
this.zkPath = path;
} catch (Exception e) {
logger.error("Register fail, exception: {}.", e.getMessage(), e);
}
this.zkClient.watchPathChildrenNode(NameSpaceEnum.ZK_REGISTRY_PATH.getValue(), new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) {
PathChildrenCacheEvent.Type type = pathChildrenCacheEvent.getType();
ChildData childData = pathChildrenCacheEvent.getData();
switch(type) {
case CHILD_ADDED:
RegistryPackage rpAdd = RegistryPackage.fromJson(new String(childData.getData(), StandardCharsets.UTF_8));
Map<RegistryPackage, Channel> map = PeerServerConnectKeeper.getMap();
if (map.containsKey(rpAdd)) {
break;
}
// connect new node
Connector.connect(rpAdd.getHost(), rpAdd.getPort());
break;
case CHILD_REMOVED:
RegistryPackage rpRemove = RegistryPackage.fromJson(new String(childData.getData(), StandardCharsets.UTF_8));
// p2p delete removed node
PeerServerConnectKeeper.remove(rpRemove);
break;
}
}
});
this.zkClient.addConnectionStateListener(new ConnectionStateListener() {
@SneakyThrows
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
if (newState == ConnectionState.RECONNECTED) {
logger.info("Connection state: {}, reconnected.", newState);
registerService(RegistryCenter.host, RegistryCenter.port);
}
}
});
return activeList.isEmpty();
}
use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project blockchain by vincentbin.
the class RegistryCenter method registerService.
/**
* register server & observer active online server
* @param host local ip
* @param port local port
* @return 注册前是否有活跃线上机器
* @throws Exception zk watch
*/
public boolean registerService(String host, int port) throws Exception {
RegistryCenter.host = host;
RegistryCenter.port = port;
List<String> activeList = getServiceList();
try {
RegistryPackage registryPackage = new RegistryPackage();
registryPackage.setHost(RegistryCenter.host);
registryPackage.setPort(RegistryCenter.port);
String registryPackageJson = registryPackage.toJson();
byte[] bytes = registryPackageJson.getBytes();
String path = NameSpaceEnum.ZK_REGISTRY_PATH.getValue().concat("/node-") + registryPackage.hashCode();
path = this.zkClient.createPathData(path, bytes);
this.zkPath = path;
} catch (Exception e) {
logger.error("Register fail, exception: {}.", e.getMessage(), e);
}
this.zkClient.watchPathChildrenNode(NameSpaceEnum.ZK_REGISTRY_PATH.getValue(), new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) {
PathChildrenCacheEvent.Type type = pathChildrenCacheEvent.getType();
ChildData childData = pathChildrenCacheEvent.getData();
switch(type) {
case CHILD_ADDED:
RegistryPackage rpAdd = RegistryPackage.fromJson(new String(childData.getData(), StandardCharsets.UTF_8));
// connect new node
Connector.connect(rpAdd.getHost(), rpAdd.getPort());
break;
case CHILD_REMOVED:
RegistryPackage rpRemove = RegistryPackage.fromJson(new String(childData.getData(), StandardCharsets.UTF_8));
// p2p delete removed node
PeerServerConnectKeeper.remove(rpRemove);
break;
}
}
});
this.zkClient.addConnectionStateListener(new ConnectionStateListener() {
@SneakyThrows
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
if (newState == ConnectionState.RECONNECTED) {
logger.info("Connection state: {}, reconnected.", newState);
registerService(RegistryCenter.host, RegistryCenter.port);
}
}
});
return activeList.isEmpty();
}
use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project carapaceproxy by diennea.
the class ZooKeeperGroupMembershipHandler method watchEvent.
@Override
public void watchEvent(String eventId, EventCallback callback) {
try {
final String path = "/proxy/events";
final String eventpath = "/proxy/events/" + eventId;
LOG.info("watching " + path);
PathChildrenCache cache = new PathChildrenCache(client, path, true);
// hold a strong reference to the PathChildrenCache
watchedEvents.add(cache);
cache.getListenable().addListener((PathChildrenCacheListener) (CuratorFramework cf, PathChildrenCacheEvent pcce) -> {
LOG.log(Level.INFO, "ZK event {0} at {1}", new Object[] { pcce, path });
ChildData data = pcce.getData();
if (data != null && eventpath.equals(data.getPath())) {
byte[] content = data.getData();
LOG.log(Level.INFO, "ZK event content {0}", new Object[] { new String(content, StandardCharsets.UTF_8) });
if (content != null) {
Map<String, String> info = MAPPER.readValue(new ByteArrayInputStream(content), Map.class);
String origin = info.get("origin");
if (peerId.equals(origin)) {
LOG.log(Level.INFO, "discard self originated event " + info);
} else {
LOG.log(Level.INFO, "handle event " + info);
callback.eventFired(eventId);
}
}
} else if (pcce.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED) {
callback.reconnected();
}
}, callbacksExecutor);
cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project brpc-java by baidu.
the class DubboZookeeperNamingService method doSubscribe.
@Override
public void doSubscribe(SubscribeInfo subscribeInfo, final NotifyListener listener) throws Exception {
final String path = buildParentNodePath(subscribeInfo.getGroup(), subscribeInfo.getInterfaceName(), subscribeInfo.getVersion());
PathChildrenCache cache = new PathChildrenCache(client, path, true);
cache.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
ChildData data = event.getData();
// 子节点信息,将监听的父节点信息擦除
String childNodePath = data.getPath().replace(path + "/", "");
String providerUrlString = URLDecoder.decode(childNodePath, "UTF-8");
BrpcURL url = new BrpcURL(providerUrlString);
ServiceInstance instance = new ServiceInstance(url.getHostPorts());
switch(event.getType()) {
case CHILD_ADDED:
{
listener.notify(Collections.singletonList(instance), Collections.<ServiceInstance>emptyList());
break;
}
case CHILD_REMOVED:
{
listener.notify(Collections.<ServiceInstance>emptyList(), Collections.singletonList(instance));
break;
}
case CHILD_UPDATED:
default:
break;
}
}
});
cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
subscribeCacheMap.putIfAbsent(subscribeInfo, cache);
log.info("dubbo subscribe success from {}", url);
}
Aggregations