zookeeper的javaAPI的增删查改和监听事件的持续监听

zookeeper的增删查改操作调用原生javaAPI实现,重点是对节点数据的监听,讲一下设计方案,把新加入的监听包装成一个类,主要属性有监听的具体节点路径和回调函数的具体操作。

内部类:

public static abstract class Subscriber {
		abstract String target();

		abstract void process(WatchedEvent event,String newValue);
	}

操作demo中保存一个关于Subscriber的List,在每次监听事件中遍历这个监听列表,如果路径一样,那么执行相应的操作函数。由于zookeeper是单次监听的,所以在每次监听执行后再次监听此节点。

所以主要的监听流程为:

private static ZooKeeper zooKeeper;
	private static final List<Subscriber> subscribers = new ArrayList<>();
	private CountDownLatch latch = new CountDownLatch(1);

	@Override
	public void process(WatchedEvent watchedEvent) {
		if (watchedEvent.getState().equals(Event.KeeperState.SyncConnected)) {
			//init done
			latch.countDown();
		} else if (watchedEvent.getState().equals(Event.KeeperState.Disconnected)) {
			System.out.println("Disconnected!");
		}
		//foreach
		synchronized (subscribers) {
			for (Subscriber subscribe : subscribers) {
				if (subscribe.target().equals(watchedEvent.getPath())) {
					try {
						//listening again
						String data = new String(zooKeeper.getData(watchedEvent.getPath(),true,null),"utf-8");
						subscribe.process(watchedEvent,data);
					} catch (KeeperException e) {
						e.printStackTrace();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * command : get path watch
	 */
	public boolean addSubscriber(Subscriber subscriber) {
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		}
		//add a subscriber
		synchronized (subscribers) {
			subscribers.add(subscriber);
		}
		try {
			//start listener
			zooKeeper.getData(subscriber.target(), true, null);
		} catch (KeeperException e) {
			e.printStackTrace();
			return false;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

代码演示:

开始监听:

开一个命令窗口修改值:

监听事件响应:

持续监听:

附上完成实现代码:

package cn.wzy.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * zookeeper listener demo
 */
public class ListenerDemo implements Watcher {
	public static abstract class Subscriber {
		abstract String target();

		abstract void process(WatchedEvent event,String newValue);
	}

	private static ZooKeeper zooKeeper;
	private static final List<Subscriber> subscribers = new ArrayList<>();
	private CountDownLatch latch = new CountDownLatch(1);

	@Override
	public void process(WatchedEvent watchedEvent) {
		if (watchedEvent.getState().equals(Event.KeeperState.SyncConnected)) {
			//init done
			latch.countDown();
		} else if (watchedEvent.getState().equals(Event.KeeperState.Disconnected)) {
			System.out.println("Disconnected!");
		}
		//foreach
		synchronized (subscribers) {
			for (Subscriber subscribe : subscribers) {
				if (subscribe.target().equals(watchedEvent.getPath())) {
					try {
						//listening again
						String data = new String(zooKeeper.getData(watchedEvent.getPath(),true,null),"utf-8");
						subscribe.process(watchedEvent,data);
					} catch (KeeperException e) {
						e.printStackTrace();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * command : get path watch
	 */
	public boolean addSubscriber(Subscriber subscriber) {
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		}
		//add a subscriber
		synchronized (subscribers) {
			subscribers.add(subscriber);
		}
		try {
			//start listener
			zooKeeper.getData(subscriber.target(), true, null);
		} catch (KeeperException e) {
			e.printStackTrace();
			return false;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * command : get path
	 */
	public static String get(String znode, boolean watch,String charset) {
		try {
			return new String(zooKeeper.getData(znode,watch,null),charset);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * command : set path data
	 */
	public static Stat set(String znode, String data, int version) {
		try {
			return zooKeeper.setData(znode,data.getBytes(),version);
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * command : create path data [createMode]
	 */
	public static String create(String znode, String data, CreateMode createMode) {
		try {
			return zooKeeper.create(znode, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode);
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * command : ls path
	 */
	public static Stat exists(String znode, boolean watch) {
		try {
			zooKeeper.exists(znode, watch);
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * command : delete path data
	 */
	public static void delete(String znode) {
		try {
			zooKeeper.delete(znode, -1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (KeeperException e) {
			e.printStackTrace();
		}
	}

	public ListenerDemo(String url, Integer timeOut) throws IOException {
		zooKeeper = new ZooKeeper(url, timeOut, this);
	}

	public static void main(String[] args) throws IOException, InterruptedException {
		ListenerDemo demo = new ListenerDemo("192.168.0.115:2181", 500);
		boolean res = demo.addSubscriber(new Subscriber() {
			@Override
			String target() {
				return "/config/aaa/bbb";
			}

			@Override
			void process(WatchedEvent event, String newValue) {
				System.out.println(target() + ", the new value is : " + newValue);
			}
		});
		System.out.println(res);
		while (true) {
			//set("/config/aaa/bbb",System.currentTimeMillis() + "",-1);
			Thread.sleep(2000);
		}
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值