5.模拟美团商家上下线
5.1 需求
- 模拟美团服务平台,商家营业通知,商家打烊通知
- 提前在根节点下,创建好 /meituan 节点
5.2 商家服务类
public class ShopServer {
private static String connectString = "192.168.204.141:2181,192.168.204.142:2181,192.168.204.143:2181";
private static int sessionTimeout = 60000;
private ZooKeeper zk = null;
// 创建到zk的客户端连接
public void getConnect() throws IOException {
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent event) {
}
});
}
// 注册到集群
public void register(String ShopName) throws Exception {
// 一定是"EPHEMERAL_SEQUENTIAL短暂有序型"的节点,才能给shop编号,shop1, shop2...”
String create = zk.create("/meituan/Shop", ShopName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println("【"+ShopName+"】 开始营业! " + create);
}
// 业务功能
public void business(String ShopName) throws Exception {
System.out.println("【"+ShopName+"】 正在营业中 ...");
System.in.read();
}
public static void main(String[] args) throws Exception {
ShopServer shop = new ShopServer();
// 1.连接zookeeper集群(和美团取得联系)
shop.getConnect();
// 2.将服务器节点注册(入住美团)
shop.register(args[0]);
// 3.业务逻辑处理(做生意)
shop.business(args[0]);
}
}
5.3 客户类
public class Customers {
private static String connectString = "192.168.204.141:2181,192.168.204.142:2181,192.168.204.143:2181";
private static int sessionTimeout = 60000;
private ZooKeeper zk = null;
// 创建到zk的客户端连接
public void getConnect() throws IOException {
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent event) {
// 再次获取所有商家
try {
getShopList();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
// 获取服务器列表信息
public void getShopList() throws Exception {
// 1获取服务器子节点信息,并且对父节点进行监听
List<String> shops = zk.getChildren("/meituan", true);
// 2存储服务器信息列表
ArrayList<String> shoplist = new ArrayList();
// 3遍历所有节点,获取节点中的主机名称信息
for (String shop : shops) {
byte[] data = zk.getData("/meituan/" + shop, false, new Stat());
shoplist.add(new String(data));
}
// 4打印服务器列表信息
System.out.println(shoplist);
}
// 业务功能
public void business() throws Exception {
System.out.println("客户正在浏览商家 ...");
System.in.read();
}
public static void main(String[] args) throws Exception {
// 1.获取zk连接 (客户打开美团)
Customers client = new Customers();
client.getConnect();
// 2.获取/meituan的子节点信息,从中获取服务器信息列表(从美团中获取商家列表)
client.getShopList();
// 3.业务进程启动 (对比商家,点餐)
client.business();
}
}
-
运行客户类,就会得到商家列表
-
首先在linux中添加一个商家,然后观察客户端的控制台输出(商家列表会立刻更新出最新商家),多添加几个,也会实时输出商家列表
create /meituan/KFC "KFC" create /meituan/BKC "BurgerKing" create /meituan/baozi "baozi"
-
在linux中删除商家,在客户端的控制台也会实时看到商家移除后的最新商家列表
delete /meituan/baozi
-
运行商家服务类(以main方法带参数的形式运行)