Search in sources :

Example 1 with TreeCacheListener

use of org.apache.curator.framework.recipes.cache.TreeCacheListener in project sharding-jdbc by shardingjdbc.

the class ZookeeperRegistryCenter method watch.

@Override
public void watch(final String key, final EventListener eventListener) {
    final String path = key + "/";
    if (!caches.containsKey(path)) {
        addCacheData(key);
    }
    TreeCache cache = caches.get(path);
    cache.getListenable().addListener(new TreeCacheListener() {

        @Override
        public void childEvent(final CuratorFramework client, final TreeCacheEvent event) throws Exception {
            ChildData data = event.getData();
            if (null == data || null == data.getPath()) {
                return;
            }
            eventListener.onChange(new DataChangedEvent(getEventType(event), data.getPath(), null == data.getData() ? null : new String(data.getData(), "UTF-8")));
        }

        private DataChangedEvent.Type getEventType(final TreeCacheEvent event) {
            switch(event.getType()) {
                case NODE_UPDATED:
                    return DataChangedEvent.Type.UPDATED;
                case NODE_REMOVED:
                    return DataChangedEvent.Type.DELETED;
                default:
                    return DataChangedEvent.Type.IGNORED;
            }
        }
    });
}
Also used : DataChangedEvent(io.shardingjdbc.orchestration.reg.listener.DataChangedEvent) TreeCache(org.apache.curator.framework.recipes.cache.TreeCache) CuratorFramework(org.apache.curator.framework.CuratorFramework) TreeCacheListener(org.apache.curator.framework.recipes.cache.TreeCacheListener) ChildData(org.apache.curator.framework.recipes.cache.ChildData) TreeCacheEvent(org.apache.curator.framework.recipes.cache.TreeCacheEvent) OperationTimeoutException(org.apache.zookeeper.KeeperException.OperationTimeoutException)

Example 2 with TreeCacheListener

use of org.apache.curator.framework.recipes.cache.TreeCacheListener in project elastic-job by dangdangdotcom.

the class JobNodeStorageTest method assertAddDataListener.

@Test
public void assertAddDataListener() {
    TreeCache treeCache = mock(TreeCache.class);
    @SuppressWarnings("unchecked") Listenable<TreeCacheListener> listeners = mock(Listenable.class);
    TreeCacheListener listener = mock(TreeCacheListener.class);
    when(treeCache.getListenable()).thenReturn(listeners);
    when(regCenter.getRawCache("/test_job")).thenReturn(treeCache);
    jobNodeStorage.addDataListener(listener);
    verify(listeners).addListener(listener);
}
Also used : TreeCache(org.apache.curator.framework.recipes.cache.TreeCache) TreeCacheListener(org.apache.curator.framework.recipes.cache.TreeCacheListener) Test(org.junit.Test)

Example 3 with TreeCacheListener

use of org.apache.curator.framework.recipes.cache.TreeCacheListener in project Saturn by vipshop.

the class ShardingTreeCache method addTreeCacheListenerIfAbsent.

public TreeCacheListener addTreeCacheListenerIfAbsent(String path, int depth, TreeCacheListener treeCacheListener) {
    synchronized (this) {
        TreeCacheListener treeCacheListenerOld = null;
        String key = getKey(path, depth);
        TreeCache treeCache = treeCacheMap.get(key);
        if (treeCache == null) {
            logger.error("The TreeCache is not exists, cannot add TreeCacheListener, path is {}, depth is {}", path, depth);
        } else {
            List<TreeCacheListener> treeCacheListeners = treeCacheListenerMap.get(treeCache);
            boolean included = false;
            for (TreeCacheListener tmp : treeCacheListeners) {
                Class<? extends TreeCacheListener> tmpClass = tmp.getClass();
                Class<? extends TreeCacheListener> treeCacheListenerClass = treeCacheListener.getClass();
                if (tmpClass.equals(treeCacheListenerClass)) {
                    treeCacheListenerOld = tmp;
                    included = true;
                    break;
                }
            }
            if (included) {
                logger.info("The TreeCache has already included the instance of listener, will not be added, path is {}, depth is {}, listener is {}", path, depth, treeCacheListener.getClass());
            } else {
                treeCacheListeners.add(treeCacheListener);
                treeCache.getListenable().addListener(treeCacheListener);
            }
        }
        return treeCacheListenerOld;
    }
}
Also used : TreeCache(org.apache.curator.framework.recipes.cache.TreeCache) TreeCacheListener(org.apache.curator.framework.recipes.cache.TreeCacheListener)

Example 4 with TreeCacheListener

use of org.apache.curator.framework.recipes.cache.TreeCacheListener in project Saturn by vipshop.

the class ShardingTreeCacheService method addTreeCacheListenerIfAbsent.

public void addTreeCacheListenerIfAbsent(String path, int depth, TreeCacheListener treeCacheListener) throws ShardingException {
    synchronized (isShutdownFlag) {
        if (isShutdownFlag.get()) {
            throw new ShardingException("ShardingTreeCacheService has been shutdown");
        }
        String fullPath = namespace + path;
        TreeCacheListener treeCacheListenerOld = shardingTreeCache.addTreeCacheListenerIfAbsent(path, depth, treeCacheListener);
        if (treeCacheListenerOld == null) {
            LOGGER.info("add {}, full path is {}, depth is {}", treeCacheListener.getClass().getSimpleName(), fullPath, depth);
        }
    }
}
Also used : ShardingException(com.vip.saturn.job.sharding.exception.ShardingException) TreeCacheListener(org.apache.curator.framework.recipes.cache.TreeCacheListener)

Example 5 with TreeCacheListener

use of org.apache.curator.framework.recipes.cache.TreeCacheListener in project Saturn by vipshop.

the class SaturnExecutorService method registerCallbackAndStartExistingJob.

/**
 * Register NewJobCallback, and async start existing jobs. The TreeCache will publish the create events for already
 * existing jobs.
 */
public void registerCallbackAndStartExistingJob(final ScheduleNewJobCallback callback) throws Exception {
    jobsTreeCache = TreeCache.newBuilder((CuratorFramework) coordinatorRegistryCenter.getRawClient(), JobNodePath.ROOT).setExecutor(new CloseableExecutorService(Executors.newSingleThreadExecutor(new SaturnThreadFactory(executorName + "-$Jobs-watcher", false)), true)).setMaxDepth(1).build();
    jobsTreeCache.getListenable().addListener(new TreeCacheListener() {

        @Override
        public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
            if (event == null) {
                return;
            }
            ChildData data = event.getData();
            if (data == null) {
                return;
            }
            String path = data.getPath();
            if (path == null || path.equals(JobNodePath.ROOT)) {
                return;
            }
            Type type = event.getType();
            if (type == null || !type.equals(Type.NODE_ADDED)) {
                return;
            }
            String jobName = StringUtils.substringAfterLast(path, "/");
            String jobClassPath = JobNodePath.getNodeFullPath(jobName, ConfigurationNode.JOB_CLASS);
            // wait 5 seconds at most until jobClass created.
            for (int i = 0; i < WAIT_JOBCLASS_ADDED_COUNT; i++) {
                if (client.checkExists().forPath(jobClassPath) == null) {
                    Thread.sleep(200);
                    continue;
                }
                log.info("new job: {} 's jobClass created event received", jobName);
                if (!jobNames.contains(jobName)) {
                    if (callback.call(jobName)) {
                        jobNames.add(jobName);
                        log.info("the job {} initialize successfully", jobName);
                    } else {
                        log.warn("the job {} initialize fail", jobName);
                    }
                } else {
                    log.warn("the job {} is unnecessary to initialize, because it's already existing", jobName);
                }
                break;
            }
        }
    });
    jobsTreeCache.start();
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) Type(org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type) TreeCacheListener(org.apache.curator.framework.recipes.cache.TreeCacheListener) CloseableExecutorService(org.apache.curator.utils.CloseableExecutorService) ChildData(org.apache.curator.framework.recipes.cache.ChildData) TreeCacheEvent(org.apache.curator.framework.recipes.cache.TreeCacheEvent) SaturnThreadFactory(com.vip.saturn.job.threads.SaturnThreadFactory) TimeDiffIntolerableException(com.vip.saturn.job.exception.TimeDiffIntolerableException)

Aggregations

TreeCacheListener (org.apache.curator.framework.recipes.cache.TreeCacheListener)8 TreeCache (org.apache.curator.framework.recipes.cache.TreeCache)5 CuratorFramework (org.apache.curator.framework.CuratorFramework)4 TreeCacheEvent (org.apache.curator.framework.recipes.cache.TreeCacheEvent)4 ChildData (org.apache.curator.framework.recipes.cache.ChildData)2 Test (org.junit.Test)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 TimeDiffIntolerableException (com.vip.saturn.job.exception.TimeDiffIntolerableException)1 ShardingException (com.vip.saturn.job.sharding.exception.ShardingException)1 SaturnThreadFactory (com.vip.saturn.job.threads.SaturnThreadFactory)1 DataChangedEvent (io.shardingjdbc.orchestration.reg.listener.DataChangedEvent)1 EnumMap (java.util.EnumMap)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Type (org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type)1 CloseableExecutorService (org.apache.curator.utils.CloseableExecutorService)1 TreeCacheEvent (org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.cache.TreeCacheEvent)1 TreeCacheListener (org.apache.flink.shaded.curator5.org.apache.curator.framework.recipes.cache.TreeCacheListener)1 ConfigurationType (org.apache.metron.common.configuration.ConfigurationType)1