Search in sources :

Example 56 with PathChildrenCacheEvent

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是一次性的
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache)

Example 57 with PathChildrenCacheEvent

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();
}
Also used : PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) SneakyThrows(lombok.SneakyThrows) RegistryPackage(com.polyu.blockchain.common.wrapper.RegistryPackage) CuratorFramework(org.apache.curator.framework.CuratorFramework) ChildData(org.apache.curator.framework.recipes.cache.ChildData) ConnectionState(org.apache.curator.framework.state.ConnectionState) Map(java.util.Map) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener)

Example 58 with PathChildrenCacheEvent

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();
}
Also used : PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) SneakyThrows(lombok.SneakyThrows) RegistryPackage(com.polyu.blockchain.common.wrapper.RegistryPackage) CuratorFramework(org.apache.curator.framework.CuratorFramework) ChildData(org.apache.curator.framework.recipes.cache.ChildData) ConnectionState(org.apache.curator.framework.state.ConnectionState) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener)

Example 59 with PathChildrenCacheEvent

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);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) ByteArrayInputStream(java.io.ByteArrayInputStream) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) ChildData(org.apache.curator.framework.recipes.cache.ChildData) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 60 with PathChildrenCacheEvent

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);
}
Also used : BrpcURL(com.baidu.brpc.naming.BrpcURL) CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) ChildData(org.apache.curator.framework.recipes.cache.ChildData) ServiceInstance(com.baidu.brpc.client.channel.ServiceInstance) RpcException(com.baidu.brpc.exceptions.RpcException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

PathChildrenCacheEvent (org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent)68 CuratorFramework (org.apache.curator.framework.CuratorFramework)58 PathChildrenCacheListener (org.apache.curator.framework.recipes.cache.PathChildrenCacheListener)52 PathChildrenCache (org.apache.curator.framework.recipes.cache.PathChildrenCache)36 ChildData (org.apache.curator.framework.recipes.cache.ChildData)21 IOException (java.io.IOException)15 KeeperException (org.apache.zookeeper.KeeperException)11 Test (org.junit.Test)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 DataSegment (org.apache.druid.timeline.DataSegment)5 Map (java.util.Map)4 ZKPaths (org.apache.curator.utils.ZKPaths)4 RedisConfig (cn.northpark.zookeeper.RedisConfig)3 SofaRpcRuntimeException (com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException)3 ServiceInstance (com.baidu.brpc.client.channel.ServiceInstance)3 RpcException (com.baidu.brpc.exceptions.RpcException)3 DataSegment (io.druid.timeline.DataSegment)3 Releasable (com.ctrip.xpipe.api.lifecycle.Releasable)2 RegistryPackage (com.polyu.blockchain.common.wrapper.RegistryPackage)2 ServiceDTO (io.fabric8.gateway.ServiceDTO)2