大数据教程(3.9):zookeeper分布式应用系统服务器上下线动态感知程序开发_

    以前在zookeeper介绍时,有提到过zookeeper的应用场景有服务器上下线动态感知、分布式共享锁等等。本节博主将为你们提供一个分布式服务动态感知的事例,在后期博主的开源项目中的本身开发远程分布式框架rpc服务也将使用。因此,你们必定要掌握这块知识点。java

    对于还不清楚动态感知原理的请先看以前的文章大数据教程(3.3):zookeeper简介apache

(1)分布式服务端注册centos

package com.empire.zookeeper.test.em_zookeeper.zkdist;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.ZooKeeper;

public class DistributedServer {
	private static final String connectString = "centos-aaron-07:2181,centos-aaron-08:2181,centos-aaron-16:2181";
	private static final int sessionTimeout = 2000;
	private static final String parentNode = "/servers";
	private CountDownLatch connectedSemaphore = new CountDownLatch(1); 
	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) {
				// 收到事件通知后的回调函数(应该是咱们本身的事件处理逻辑)
				System.out.println(event.getType() + "---" + event.getPath());
				try {
					zk.getChildren("/", true);
					connectedSemaphore.countDown(); 
				} catch (Exception e) {
				}
			}
		});
		connectedSemaphore.await();
	}

	/**
	 * 向zk集群注册服务器信息
	 * 
	 * @param hostname
	 * @throws Exception
	 */
	public void registerServer(String hostname) throws Exception {
		Stat stat = zk.exists(parentNode, false);
		System.out.println(stat==null?"not exist":"exist");
		if(stat==null) {
			String parentNodeCreate = zk.create(parentNode , null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		}

		String create = zk.create(parentNode + "/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
		System.out.println(hostname + "is online.." + create);

	}

	/**
	 * 业务功能
	 * 
	 * @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 {

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

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

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

	}

}

(2)分布式客户端感知服务状态服务器

package com.empire.zookeeper.test.em_zookeeper.zkdist;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class DistributedClient {

	private static final String connectString = "centos-aaron-07:2181,centos-aaron-08:2181,centos-aaron-16:2181";
	private static final int sessionTimeout = 2000;
	private static final String parentNode = "/servers";
	// 注意:加volatile的意义何在?
	private volatile List<String> serverList;
	private CountDownLatch connectedSemaphore = new CountDownLatch(1); 
	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();
					connectedSemaphore.countDown(); 
				} catch (Exception e) {
				}
			}
		});
		connectedSemaphore.await();
	}

	/**
	 * 获取服务器信息列表
	 * 
	 * @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();
		
	}

}

    注意点:在启动server端上线时,须要输入启动参数hostname来启动,该值用来惟一标识当前上线的是哪台服务。session

    最后总结:其实分布式服务动态感知主要运行zookeeper的短暂节点的的特性(服务器下线,zookeeper会自动删除该服务器对于的临时节点信息,并通知其它监听了该节点变化的客户端)来实现感知动态下线,以及zookeeper的节点监听事件功能来实现感知服务动态上线。框架

    最后寄语,以上是博主本次文章的所有内容,若是你们以为博主的文章还不错,请点赞;若是您对博主其它服务器技术或者博主本人感兴趣,请关注博主博客,而且欢迎随时跟博主沟通交流。分布式

相关文章
相关标签/搜索