分布式应用系统服务上下线动态感知程序开发

需求描述:
服务器会有动态上下线的情况,客户端需要知道服务端到底有哪几台,需要感知服务器是否宕机.

前提知识点:

项目代码:
https://gitee.com/tanghongping/bd-zkAPI

package com.thp.bigdata.zkdst;

public class Test {
	
	public static void main(String[] args) {
		System.out.println("主线程开始了...");
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("线程开始了...");
				while(true) {
					
				}
			}
		}).start();;
	}
}

上面的程序会一直运行着,因为主线程停止之后,另外还有一个线程进入的是死循环
守护线程:主线程退出了,守护线程也会退出:

package com.thp.bigdata.zkdst;

public class Test {
	
	public static void main(String[] args) {
		System.out.println("主线程开始了...");
		
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("线程开始了...");
				while(true) {
					
				}
			}
		});
		thread.setDaemon(true);
		thread.start();
	}
}

上面的这段代码不会一直进入死循环,主线程结束之后,守护线程也会结束


分布式系统的服务端:

package com.thp.bigdata.zkdst;

import java.io.IOException;

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

/**
 * 分布式系统的服务端
 * @author tommy
 *
 */
public class DistributeServer {

	
	
	private static final String connectString = "bd1:2181,bd2:2181,bd3:2181";
	// 超时时间
	private static final int sessionTimeout = 2000;
	
	private static final String parentNode = "/servers";
	
	
	
	private ZooKeeper zk = null;
	
	
	/**
	 * 创建到zk的客户端连接
	 * @throws IOException
	 */
	public void getConnect() throws IOException {
		zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				// 收到事件通知后的回调函数 (应该是我们自己的事件处理逻辑)
				System.out.println(event.getType() + " -- " + event.getPath()); // 事件的类型  --   事件发生的节点
				try {
					// getChildren 只是为了 设置这个监听  相当于又监听了
					zk.getChildren("/", true);
				} catch (KeeperException | InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	
	
	/**
	 * 判断节点是否存在
	 * @param node
	 * @return
	 * @throws KeeperException
	 * @throws InterruptedException
	 */
	public boolean isExist(String node) throws KeeperException, InterruptedException {
		Stat stat = zk.exists(node, false);
		return stat == null ? false : true;
	}
	
	/**
	 * 创建节点
	 * @param node
	 * @throws KeeperException
	 * @throws InterruptedException
	 */
	public void createNode(String node) throws KeeperException, InterruptedException {
		zk.create(node, "server-node".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
	}

	/**
	 * 向zk集群注册服务器信息
	 * @param hostname
	 * @throws KeeperException
	 * @throws InterruptedException
	 */
	public void registerServer(String hostname) throws KeeperException, InterruptedException {
		if(!isExist(parentNode)) {  // 父节点不存在则创建节点
			createNode(parentNode);
		}
		
		// 节点类型是临时的带序号的   这样可以保证不会冲突
		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 + "is working...");
		Thread.sleep(Long.MAX_VALUE);
	}
	
	
	public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
		// 1.获取zk连接  
		DistributeServer server = new DistributeServer();
		server.getConnect();
		// 2.利用zk连接注册服务器信息
		server.registerServer(args[0]);
		// 3.启动业务功能
		server.handleBussiness(args[0]);
	}
	
	
}

分布式系统的客户端:

package com.thp.bigdata.zkdst;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

/**
 * 分布式系统的客户端
 * @author tommy
 *
 */
public class DistributeClient {

	private static final String connectString = "bd1:2181,bd2:2181,bd3:2181";
	// 超时时间
	private static final int sessionTimeout = 2000;
	
	private static final String parentNode = "/servers";
	// 注意: 加volatile的意义何在
	private volatile List<String> serverList;
	
	
	private ZooKeeper zk = null;
	
	
	/**
	 * 创建到zk的客户端连接
	 * @throws IOException
	 */
	public void getConnect() throws IOException {
		zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				// 收到事件通知后的回调函数(应该是我们自己的事件处理逻辑)
				try {
					getServerList();  // 重新更新服务器列表,并且注册了监听 下次发生这种时间 还是会被调用
				} catch (KeeperException | InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/**
	 * 获取服务器信息列表
	 * @throws InterruptedException 
	 * @throws KeeperException 
	 */
	public void getServerList() throws KeeperException, InterruptedException {
		// 获取服务器子节点信息  并且对父节点进行监听   一旦发生了变化,那么process就会被调用
		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 IOException, KeeperException, InterruptedException {
		// 1.获取zookeeper连接
		DistributeClient client = new DistributeClient();
		client.getConnect();
		// 2.获取servers的子节点信息(并监听),从中获取服务器信息列表
		client.getServerList();
		// 3.业务线程启动
		client.handleBussiness();
	}	
}

两个程序的代码都写好了,那么将程序打成jar包:
1.将DistributeServer打成jar包 – (要运行之后才能选择打成jar包)
在这里插入图片描述

在这里插入图片描述

eclipse 导出可运行jar包时三种Library handling的区别:
https://blog.csdn.net/qq_21808961/article/details/81185934

2.将DistributeClient打成jar包,要先运行一遍:
在这里插入图片描述

打成的jar包:
在这里插入图片描述

测试效果:在windows上运行:
在这里插入图片描述
可以做到实时感知服务的上下线

猜你喜欢

转载自blog.csdn.net/qq_38200548/article/details/82934172