监听2

代码如下:

 

package com.bw.ZK;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
//1.服务器在运行状态下完成  不能停
//2.服务器中的数据信息要进行更新 (2 8)
//3.通过动态监听的形式进行更新
// 短信接口  把短信介入到 电信 移动 联通
 //  账号 密码  介入地址  平台类型
// www.yidong.com/message;bw;admin;yidong
//4.动态监听。。。
//zk 挂载  短信时间-----》反应时间-----》数据被修改  监听到
public class infomessage {
	static String zkUrl="linux04:2181";
	static int timeout=5000;//反应时间
	static String Url=null;//客户端的的url
	static String infopath="/info1";//挂载的路径
	static String username=null;
	static String password=null;
	static String platfromtype=null;
	static ZooKeeper zk=null;
	public static void main(String[] args) throws Exception {
		//创建连接对象
		zk = new ZooKeeper(zkUrl,timeout, new Watcher() {
			@Override
			public void process(WatchedEvent arg0) {
				if(arg0.getType()==EventType.NodeDataChanged) {
					byte[] info=null;
					try {
						info = zk.getData(infopath, true, new Stat());
					} catch (Exception e) {
						e.printStackTrace();
					}
					String infoMessage= new String(info);
					String[] split = infoMessage.split(";");
					Url=split[0];
					username=split[1];
					password=split[2];
					platfromtype=split[3];
				}
			}});
		//对挂载的数据改变
		byte[] info = zk.getData(infopath, true, new Stat());
		String infoMessage= new String(info);
		String[] split = infoMessage.split(";");
		Url=split[0];
		username=split[1];
		password=split[2];
		platfromtype=split[3];
		//服务端 每5秒发一次
		while(true) {
			Thread.sleep(5000);
			System.err.println("now is send message"+
			"platfromtype="+platfromtype+
			"username="+username+
			"password="+password+
			"url="+Url);
		}				
	}
}

  

 

原文地址:https://www.cnblogs.com/JBLi/p/10726807.html