zookeeper动态感知服务器的增加和减少

本文详细介绍了如何使用Zookeeper实现服务发现,通过Java代码示例展示了服务端在启动时向Zookeeper注册信息,以及客户端如何监听并获取服务列表,实现自动感知服务增减的变化。

业务服务器经常会出现动态的增减,现在让客户端能够自动感知到服务端的在线服务器(此时的服务端和客户端都是Java程序,客户端可以是一个接口项目,负责转发前端的的请求和服务器的响应)

 

首先看下图,

 在每台服务器中的系统中写一段逻辑,让系统启动的时候,向zookeeper中注册,客户端启动的时候,向zookeeper中注册监听:监听子节点的数量变化。

 

服务端

public class DistributedServer {
	//zookeeper集群
	private static final String CONNECT_STRING = "mini1:2181,mini2:2181,mini3:2181";
	private static final int SESSION_TIME_OUT = 2000;
	private static final String PARENT_NODE = "/servers";

	private ZooKeeper zk = null;
	
	CountDownLatch countDownLatch = new CountDownLatch(1);

	/**
	 * 创建到zk的客户端连接
	 * 
	 * @throws Exception
	 */
	public void getConnect() throws Exception {

		zk = new ZooKeeper(CONNECT_STRING, SESSION_TIME_OUT, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				if(event.getState()==KeeperState.SyncConnected){
					countDownLatch.countDown();
				}
			}
		});
		countDownLatch.await();

	}

	/**
	 * 向zk集群注册服务器信息
	 * 
	 * @param hostname
	 * @throws Exception
	 */
	public void registerServer(String hostname) throws Exception {
		Stat exists = zk.exists(PARENT_NODE, false);
		if(exists==null) zk.create(PARENT_NODE, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		String path = zk.create(PARENT_NODE + "/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
		System.out.println(hostname + "is online.." + path);

	}

	/**
	 * 业务功能
	 * 
	 * @throws InterruptedException
	 */
	public void handleBussiness(String hostname) throws InterruptedException {
		System.out.println(hostname + "start working.....");
		Thread.sleep(Long.MAX_VALUE);
	}

	public static void main(String[] args) throws Exception {

		DistributedServer server = new DistributedServer();
		// 获取zk连接
		server.getConnect();

		// 利用zk连接注册服务器信息(主机名)
		server.registerServer(args[0]);

		// 启动业务功能
		server.handleBussiness(args[0]);

	}

}

 

客户端代码

public class DistributedClient {

	private static final String connectString = "mini1:2181,mini2:2181,mini3:2181";
	private static final int sessionTimeout = 2000;
	private static final String parentNode = "/servers";
	private volatile List<String> serverList;
	private ZooKeeper zk = null;

	/**
	 * 创建到zk的客户端连接
	 * 
	 * @throws Exception
	 */
	public void getConnect() throws Exception {

		zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				// 收到事件通知后的回调函数(应该是我们自己的事件处理逻辑)
				try {
					//重新更新服务器列表,并且注册了监听
					getServerList();

				} catch (Exception e) {
				}
			}
		});

	}

	/**
	 * 获取服务器信息列表
	 * 
	 * @throws Exception
	 */
	public void getServerList() throws Exception {

		// 获取服务器子节点信息,并且对父节点进行监听
		List<String> children = zk.getChildren(parentNode, true);

		// 先创建一个局部的list来存服务器信息
		List<String> servers = new ArrayList<String>();
		for (String child : children) {
			// child只是子节点的节点名
			byte[] data = zk.getData(parentNode + "/" + child, false, null);
			servers.add(new String(data));
		}
		// 把servers赋值给成员变量serverList,已提供给各业务线程使用
		serverList = servers;
		
		//打印服务器列表
		System.out.println(serverList);
		
	}

	/**
	 * 业务功能
	 * 
	 * @throws InterruptedException
	 */
	public void handleBussiness() throws InterruptedException {
		System.out.println("client start working.....");
		Thread.sleep(Long.MAX_VALUE);
	}
	
	
	
	
	public static void main(String[] args) throws Exception {

		// 获取zk连接
		DistributedClient client = new DistributedClient();
		client.getConnect();
		// 获取servers的子节点信息(并监听),从中获取服务器信息列表
		client.getServerList();

		// 业务线程启动
		client.handleBussiness();
		
	}

}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小江小河点、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值