org.I0Itec.zkclient.IZkStateListener Java Examples

The following examples show how to use org.I0Itec.zkclient.IZkStateListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZkclientZookeeperClient.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
public ZkclientZookeeperClient(URL url) {
    super(url);
    client = new ZkClientWrapper(url.getBackupAddress(), 30000);
    client.addListener(new IZkStateListener() {
        @Override
        public void handleStateChanged(KeeperState state) throws Exception {
            ZkclientZookeeperClient.this.state = state;
            if (state == KeeperState.Disconnected) {
                stateChanged(StateListener.DISCONNECTED);
            } else if (state == KeeperState.SyncConnected) {
                stateChanged(StateListener.CONNECTED);
            }
        }

        @Override
        public void handleNewSession() throws Exception {
            stateChanged(StateListener.RECONNECTED);
        }
    });
    client.start();
}
 
Example #2
Source File: ZookeeperRegistry.java    From mango with Apache License 2.0 6 votes vote down vote up
public ZookeeperRegistry(URL url, ZkClient zkClient) {
    super(url);
    this.zkClient = zkClient;
    IZkStateListener zkStateListener = new IZkStateListener() {
        @Override
        public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception {
            // do nothing
        }

        @Override
        public void handleNewSession() throws Exception {
            logger.info("zkRegistry get new session notify.");

        }

        @Override
        public void handleSessionEstablishmentError(Throwable throwable) throws Exception {

        }
    };
    this.zkClient.subscribeStateChanges(zkStateListener);
}
 
Example #3
Source File: ZkclientZookeeperClient.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public ZkclientZookeeperClient(URL url) {
	super(url);
	client = new ZkClient(
               url.getBackupAddress(),
               url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT),
               url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_REGISTRY_CONNECT_TIMEOUT));
	client.subscribeStateChanges(new IZkStateListener() {
		public void handleStateChanged(KeeperState state) throws Exception {
			ZkclientZookeeperClient.this.state = state;
			if (state == KeeperState.Disconnected) {
				stateChanged(StateListener.DISCONNECTED);
			} else if (state == KeeperState.SyncConnected) {
				stateChanged(StateListener.CONNECTED);
			}
		}
		public void handleNewSession() throws Exception {
			stateChanged(StateListener.RECONNECTED);
		}
	});
}
 
Example #4
Source File: ZkclientZookeeperClient.java    From JobX with Apache License 2.0 6 votes vote down vote up
public ZkclientZookeeperClient(URL url) {
    super(url);
    client = new ZkClient(url.getBackupAddress(), Constants.ZK_CONNECTION_TIMEOUT);
    client.subscribeStateChanges(new IZkStateListener() {
        public void handleStateChanged(KeeperState state) throws Exception {
            ZkclientZookeeperClient.this.state = state;
            if (state == KeeperState.Disconnected) {
                stateChanged(StateListener.DISCONNECTED);
            } else if (state == KeeperState.SyncConnected) {
                stateChanged(StateListener.CONNECTED);
            }
        }

        public void handleNewSession() throws Exception {
            stateChanged(StateListener.RECONNECTED);
        }

        @Override
        public void handleSessionEstablishmentError(Throwable throwable) throws Exception {

        }
    });
}
 
Example #5
Source File: ZkClientRegisterCenter.java    From elephant with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
	this.zkClient = new ZkClient(this.zkAddress, this.zkSessionTimeOut, this.zkConnectionTimeOut, new SerializableSerializer());
	initRootPath();
	this.zkClient.subscribeStateChanges(new IZkStateListener() {
		@Override
		public void handleStateChanged(KeeperState state) throws Exception {
			if(zkReconnectionListener != null && state.name().equals(KeeperState.SyncConnected.name())){
				zkReconnectionListener.handleStateForSyncConnected();
			}
		}
		@Override
		public void handleSessionEstablishmentError(Throwable error)throws Exception {
			log.error("处理会话建立错误:{}",error);
		}
		@Override
		public void handleNewSession() throws Exception {
			log.info("会话建立成功!");
		}
	});
}
 
Example #6
Source File: ZkclientZookeeperClient.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public ZkclientZookeeperClient(URL url) {
	super(url);
	client = new ZkClient(
               url.getBackupAddress(),
               url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT),
               url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_REGISTRY_CONNECT_TIMEOUT));
	client.subscribeStateChanges(new IZkStateListener() {
		public void handleStateChanged(KeeperState state) throws Exception {
			ZkclientZookeeperClient.this.state = state;
			if (state == KeeperState.Disconnected) {
				stateChanged(StateListener.DISCONNECTED);
			} else if (state == KeeperState.SyncConnected) {
				stateChanged(StateListener.CONNECTED);
			}
		}
		public void handleNewSession() throws Exception {
			stateChanged(StateListener.RECONNECTED);
		}
	});
}
 
Example #7
Source File: ZooKeeperRegistry.java    From light-4j with Apache License 2.0 6 votes vote down vote up
public ZooKeeperRegistry(URL url, ZooKeeperClient client) {
    super(url);
    this.client = client;
    IZkStateListener zkStateListener = new IZkStateListener() {
        @Override
        public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception {
            // do nothing
        }

        @Override
        public void handleNewSession() throws Exception {
            if(logger.isInfoEnabled()) logger.info("zkRegistry get new session notify.");
            reconnectService();
        }
    };
    client.subscribeStateChanges(zkStateListener);
}
 
Example #8
Source File: TaskStatusManager.java    From DataLink with Apache License 2.0 6 votes vote down vote up
public TaskStatusManager(TaskStatusService taskStatusService) {
    this.taskStatusService = taskStatusService;
    this.taskStatusMap = new ConcurrentHashMap<>();
    this.zkStateListener = new IZkStateListener() {
        @Override
        public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception {
            logger.info("received handle state changed event.");
        }

        @Override
        public void handleNewSession() throws Exception {
            logger.info("received handle new session event.");
            reRegisterStatus();
        }

        @Override
        public void handleSessionEstablishmentError(Throwable error) throws Exception {
            logger.error("handleSessionEstablishmentError is : " + error);
        }
    };
}
 
Example #9
Source File: ZclientChange.java    From javabase with Apache License 2.0 6 votes vote down vote up
private static void test() {
    final ZkClient zkClient = new ZkClient("localhost:2181");

    zkClient.subscribeStateChanges(new IZkStateListener() {
        @Override
        public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception {
            //当zookeeper被关闭时候 会触发这个事件
            if (state == Watcher.Event.KeeperState.Disconnected) {
              log.info("Disconnected");
            } else if (state == Watcher.Event.KeeperState.SyncConnected) {
                //  当zookeeper被重新连接的时候 会触发这个事件
                log.info("SyncConnected");
            }
        }
        @Override
        public void handleNewSession() throws Exception {
            log.info("handleNewSession");
        }

        @Override
        public void handleSessionEstablishmentError(Throwable error) throws Exception {
            log.info("handleSessionEstablishmentError");
        }
    });
}
 
Example #10
Source File: ZkclientZookeeperClient.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public ZkclientZookeeperClient(URL url) {
	super(url);
	client = new ZkClient(
               url.getBackupAddress(),
               url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT),
               url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_REGISTRY_CONNECT_TIMEOUT));
	client.subscribeStateChanges(new IZkStateListener() {
		public void handleStateChanged(KeeperState state) throws Exception {
			ZkclientZookeeperClient.this.state = state;
			if (state == KeeperState.Disconnected) {
				stateChanged(StateListener.DISCONNECTED);
			} else if (state == KeeperState.SyncConnected) {
				stateChanged(StateListener.CONNECTED);
			}
		}
		public void handleNewSession() throws Exception {
			stateChanged(StateListener.RECONNECTED);
		}
	});
}
 
Example #11
Source File: ZkClientZkClient.java    From light-task-scheduler with Apache License 2.0 6 votes vote down vote up
public ZkClientZkClient(Config config) {
    String registryAddress = NodeRegistryUtils.getRealRegistryAddress(config.getRegistryAddress());
    zkClient = new ZkClient(registryAddress, connectionTimeout);

    zkClient.subscribeStateChanges(new IZkStateListener() {

        public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception {
            ZkClientZkClient.this.state = state;
            if (state == KeeperState.Disconnected) {
                stateChanged(StateListener.DISCONNECTED);
            } else if (state == KeeperState.SyncConnected) {
                stateChanged(StateListener.CONNECTED);
            } else if (state == KeeperState.Expired) {
                stateChanged(StateListener.DISCONNECTED);
            }
        }

        public void handleNewSession() throws Exception {
            stateChanged(StateListener.RECONNECTED);
        }
    });
}
 
Example #12
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void fireSessionEstablishmentError(final Throwable error) {
    for (final IZkStateListener stateListener : _stateListener) {
        _eventThread.send(new ZkEventThread.ZkEvent("Session establishment error(" + error + ") sent to " + stateListener) {

            @Override
            public void run() throws Exception {
                stateListener.handleSessionEstablishmentError(error);
            }
        });
    }
}
 
Example #13
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void fireStateChangedEvent(final KeeperState state) {
    for (final IZkStateListener stateListener : _stateListener) {
        _eventThread.send(new ZkEventThread.ZkEvent("State changed to " + state + " sent to " + stateListener) {

            @Override
            public void run() throws Exception {
                stateListener.handleStateChanged(state);
            }
        });
    }
}
 
Example #14
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void fireNewSessionEvents() {
    for (final IZkStateListener stateListener : _stateListener) {
        _eventThread.send(new ZkEventThread.ZkEvent("New session event sent to " + stateListener) {

            @Override
            public void run() throws Exception {
                stateListener.handleNewSession();
            }
        });
    }
}
 
Example #15
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void fireNewSessionEvents() {
    for (final IZkStateListener stateListener : _stateListener) {
        _eventThread.send(new ZkEventThread.ZkEvent("New session event sent to " + stateListener) {

            @Override
            public void run() throws Exception {
                stateListener.handleNewSession();
            }
        });
    }
}
 
Example #16
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void fireStateChangedEvent(final KeeperState state) {
    for (final IZkStateListener stateListener : _stateListener) {
        _eventThread.send(new ZkEventThread.ZkEvent("State changed to " + state + " sent to " + stateListener) {

            @Override
            public void run() throws Exception {
                stateListener.handleStateChanged(state);
            }
        });
    }
}
 
Example #17
Source File: ZkClient.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private void fireSessionEstablishmentError(final Throwable error) {
    for (final IZkStateListener stateListener : _stateListener) {
        _eventThread.send(new ZkEventThread.ZkEvent("Session establishment error(" + error + ") sent to " + stateListener) {

            @Override
            public void run() throws Exception {
                stateListener.handleSessionEstablishmentError(error);
            }
        });
    }
}
 
Example #18
Source File: ZkclientZookeeperClient.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public ZkclientZookeeperClient(URL url) {
	super(url);
	client = new ZkClient(
               url.getBackupAddress(),
               url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT),
               url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_REGISTRY_CONNECT_TIMEOUT));
	client.subscribeStateChanges(new IZkStateListener() {
		public void handleStateChanged(KeeperState state) throws Exception {
			ZkclientZookeeperClient.this.state = state;
			if (state == KeeperState.Disconnected) {
				stateChanged(StateListener.DISCONNECTED);
			} else if (state == KeeperState.SyncConnected) {
				stateChanged(StateListener.CONNECTED);
			}
		}
		public void handleNewSession() throws Exception {
               stateChanged(StateListener.RECONNECTED);
           }

           //@Override
           public void handleSessionEstablishmentError(Throwable error) throws Exception {
               //TODO list...
               logger.error("zookeeper connection error!", error);
               throw new Exception(error);
           }
	});
}
 
Example #19
Source File: ZooKeeperClientImpl.java    From light-4j with Apache License 2.0 4 votes vote down vote up
@Override
public void subscribeStateChanges(IZkStateListener listener) {
    zkClient.subscribeStateChanges(listener);
}
 
Example #20
Source File: BrokerOffsetService.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void start() throws IOException {
	
	//
	if ( !running.compareAndSet(false, true) ) {
		return;
	}
	
	//
	String localIpPath = zkPathUtil.getClusterHostPath( localIp );
	initialize(  localIpPath  );
	
	 // 创建所有工作节点
	this.zkclientx.subscribeStateChanges(new IZkStateListener() {
		public void handleStateChanged(KeeperState state) throws Exception {}
		public void handleNewSession() throws Exception {
			initialize( path );
		}

		@Override
		public void handleSessionEstablishmentError(Throwable error) throws Exception {
			LOGGER.error("failed to connect to zookeeper", error);
		}
	});

	if (runningMonitor != null && !runningMonitor.isStart()) {
		runningMonitor.start();
	}
	
	
	// flush
	// 
	executorService.scheduleAtFixedRate(new Runnable() {
		@Override
		public void run() {
			try {
				if ( runningMonitor != null && runningMonitor.isMineRunning() && localAdmin != null ) {
					localAdmin.flushAll();
				}

			} catch (Exception e) {
				LOGGER.warn("offset flush err: ", e);
			}
		}
	}, 30, 30, TimeUnit.SECONDS);

}
 
Example #21
Source File: CanalController.java    From canal with Apache License 2.0 4 votes vote down vote up
public void start() throws Throwable {
    logger.info("## start the canal server[{}({}):{}]", ip, registerIp, port);
    // 创建整个canal的工作节点
    final String path = ZookeeperPathUtils.getCanalClusterNode(registerIp + ":" + port);
    initCid(path);
    if (zkclientx != null) {
        this.zkclientx.subscribeStateChanges(new IZkStateListener() {

            public void handleStateChanged(KeeperState state) throws Exception {

            }

            public void handleNewSession() throws Exception {
                initCid(path);
            }

            @Override
            public void handleSessionEstablishmentError(Throwable error) throws Exception {
                logger.error("failed to connect to zookeeper", error);
            }
        });
    }
    // 优先启动embeded服务
    embededCanalServer.start();
    // 尝试启动一下非lazy状态的通道
    for (Map.Entry<String, InstanceConfig> entry : instanceConfigs.entrySet()) {
        final String destination = entry.getKey();
        InstanceConfig config = entry.getValue();
        // 创建destination的工作节点
        if (!embededCanalServer.isStart(destination)) {
            // HA机制启动
            ServerRunningMonitor runningMonitor = ServerRunningMonitors.getRunningMonitor(destination);
            if (!config.getLazy() && !runningMonitor.isStart()) {
                runningMonitor.start();
            }
        }

        if (autoScan) {
            instanceConfigMonitors.get(config.getMode()).register(destination, defaultAction);
        }
    }

    if (autoScan) {
        instanceConfigMonitors.get(globalInstanceConfig.getMode()).start();
        for (InstanceConfigMonitor monitor : instanceConfigMonitors.values()) {
            if (!monitor.isStart()) {
                monitor.start();
            }
        }
    }

    // 启动网络接口
    if (canalServer != null) {
        canalServer.start();
    }
}
 
Example #22
Source File: ZkClient.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public void unsubscribeStateChanges(IZkStateListener stateListener) {
    synchronized (_stateListener) {
        _stateListener.remove(stateListener);
    }
}
 
Example #23
Source File: ZkClient.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public void subscribeStateChanges(final IZkStateListener listener) {
    synchronized (_stateListener) {
        _stateListener.add(listener);
    }
}
 
Example #24
Source File: ZkClient.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public ZkClient(String zkServers, int sessionTimeout, int connectionTimeout, ZkSerializer zkSerializer, IZkStateListener zkStateListener) {
    this(new ZkConnection(zkServers, sessionTimeout), connectionTimeout, zkSerializer, -1, zkStateListener);
}
 
Example #25
Source File: CanalController.java    From canal-1.1.3 with Apache License 2.0 4 votes vote down vote up
public void start() throws Throwable {
    logger.info("## start the canal server[{}:{}]", ip, port);
    // 创建整个canal的工作节点
    final String path = ZookeeperPathUtils.getCanalClusterNode(ip + ":" + port);
    initCid(path);
    if (zkclientx != null) {
        this.zkclientx.subscribeStateChanges(new IZkStateListener() {

            public void handleStateChanged(KeeperState state) throws Exception {

            }

            public void handleNewSession() throws Exception {
                initCid(path);
            }

            @Override
            public void handleSessionEstablishmentError(Throwable error) throws Exception {
                logger.error("failed to connect to zookeeper", error);
            }
        });
    }
    // 优先启动embeded服务
    embededCanalServer.start();
    // 尝试启动一下非lazy状态的通道
    for (Map.Entry<String, InstanceConfig> entry : instanceConfigs.entrySet()) {
        final String destination = entry.getKey();
        InstanceConfig config = entry.getValue();
        // 创建destination的工作节点
        if (!embededCanalServer.isStart(destination)) {
            // HA机制启动
            ServerRunningMonitor runningMonitor = ServerRunningMonitors.getRunningMonitor(destination);
            if (!config.getLazy() && !runningMonitor.isStart()) {
                runningMonitor.start();
            }
        }

        if (autoScan) {
            instanceConfigMonitors.get(config.getMode()).register(destination, defaultAction);
        }
    }

    if (autoScan) {
        instanceConfigMonitors.get(globalInstanceConfig.getMode()).start();
        for (InstanceConfigMonitor monitor : instanceConfigMonitors.values()) {
            if (!monitor.isStart()) {
                monitor.start();
            }
        }
    }

    // 启动网络接口
    if (canalServer != null) {
        canalServer.start();
    }
}
 
Example #26
Source File: ZkClient.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public void unsubscribeStateChanges(IZkStateListener stateListener) {
    synchronized (_stateListener) {
        _stateListener.remove(stateListener);
    }
}
 
Example #27
Source File: ZkClient.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public void subscribeStateChanges(final IZkStateListener listener) {
    synchronized (_stateListener) {
        _stateListener.add(listener);
    }
}
 
Example #28
Source File: ZkClient.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
public ZkClient(String zkServers, int sessionTimeout, int connectionTimeout, ZkSerializer zkSerializer, IZkStateListener zkStateListener) {
    this(new ZkConnection(zkServers, sessionTimeout), connectionTimeout, zkSerializer, -1, zkStateListener);
}
 
Example #29
Source File: ZkClient.java    From DDMQ with Apache License 2.0 3 votes vote down vote up
/**
 *
 * @param zkConnection
 *            The Zookeeper servers
 * @param connectionTimeout
 *            The connection timeout in milli seconds
 * @param zkSerializer
 *            The Zookeeper data serializer
 * @param operationRetryTimeout
 *            Most operations done through this {@link org.I0Itec.zkclient.ZkClient} are retried in cases like
 *            connection loss with the Zookeeper servers. During such failures, this
 *            <code>operationRetryTimeout</code> decides the maximum amount of time, in milli seconds, each
 *            operation is retried. A value lesser than 0 is considered as
 *            "retry forever until a connection has been reestablished".
 */
public ZkClient(final IZkConnection zkConnection, final int connectionTimeout, final ZkSerializer zkSerializer, final long operationRetryTimeout, final IZkStateListener zkStateListener) {
    if (zkConnection == null) {
        throw new NullPointerException("Zookeeper connection is null!");
    }
    _connection = zkConnection;
    _zkSerializer = zkSerializer;
    _operationRetryTimeoutInMillis = operationRetryTimeout;
    _isZkSaslEnabled = isZkSaslEnabled();
    if(zkStateListener != null) {
        subscribeStateChanges(zkStateListener);
    }

    connect(connectionTimeout, this);
}
 
Example #30
Source File: ZkClient.java    From DDMQ with Apache License 2.0 3 votes vote down vote up
/**
 *
 * @param zkConnection
 *            The Zookeeper servers
 * @param connectionTimeout
 *            The connection timeout in milli seconds
 * @param zkSerializer
 *            The Zookeeper data serializer
 * @param operationRetryTimeout
 *            Most operations done through this {@link org.I0Itec.zkclient.ZkClient} are retried in cases like
 *            connection loss with the Zookeeper servers. During such failures, this
 *            <code>operationRetryTimeout</code> decides the maximum amount of time, in milli seconds, each
 *            operation is retried. A value lesser than 0 is considered as
 *            "retry forever until a connection has been reestablished".
 */
public ZkClient(final IZkConnection zkConnection, final int connectionTimeout, final ZkSerializer zkSerializer, final long operationRetryTimeout, final IZkStateListener zkStateListener) {
    if (zkConnection == null) {
        throw new NullPointerException("Zookeeper connection is null!");
    }
    _connection = zkConnection;
    _zkSerializer = zkSerializer;
    _operationRetryTimeoutInMillis = operationRetryTimeout;
    _isZkSaslEnabled = isZkSaslEnabled();
    if(zkStateListener != null) {
        subscribeStateChanges(zkStateListener);
    }

    connect(connectionTimeout, this);
}