服务器动态上下线监听案例
4.1 需求
某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时感知到主节点服务器的上下线。
4.2 需求分析
4.3 具体 实现
服务器上线的过程对于zookeeper集群来说就是zookeeper创建目录节点的过程
package com.achang.zkcase1;
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
public class DistributeServer {
private static String connectString ="hadoop102:2181,hadoop103:2181,hadoop104:2181";
private static int sessionTimeout = 2000;
private ZooKeeper zk = null;
private String parentNode = "/servers";
public void getConnect() throws IOException{
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
}
});
}
public void registServer(String hostname) throws Exception{
String create = zk.create("/servers" + hostname,hostname.getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname +" is online "+ create);
}
public void business(String hostname) throws Exception{
System.out.println(hostname + " is working ...");
Thread.sleep(Long.MAX_VALUE);
}
public static void main(String[] args) throws Exception {
DistributeServer server = new DistributeServer();
server.getConnect();
server.registServer(args[0]);
server.business(args[0]);
}
}
package com.achang.zkcase1;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
public class DistributeClient {
private static String connectString ="hadoop102:2181,hadoop103:2181,hadoop104:2181";
private static int sessionTimeout = 2000;
private ZooKeeper zk = null;
private String parentNode = "/servers";
public void getConnect() throws IOException {
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
getServerList();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void getServerList() throws Exception {
List<String> children = zk.getChildren(parentNode, true);
ArrayList<String> servers = new ArrayList<>();
for (String child : children) {
byte[] data = zk.getData(parentNode + "/" + child,false, null);
servers.add(new String(data));
}
System.out.println(servers);
}
public void business() throws Exception{
System.out.println("client is working ...");
Thread.sleep(Long.MAX_VALUE);
}
public static void main(String[] args) throws Exception {
DistributeClient client = new DistributeClient();
client.getConnect();
client.getServerList();
client.business();
}
}
4.4 测试
ZooKeeper 分布式锁案例
什么叫做分布式锁 呢?
比如说"进程 1"在使用该资源的时候,会先去获得锁,"进程 1"获得锁以后会对该资源保持独占,这样其他进程就无法访问该资源,"进程 1"用完该资源以后就将锁释放掉,让其他进程来获得锁,那么通过这个锁机制,我们就能保证了分布式系统中多个进程能够有序的访问该临界资源。那么我们把这个分布式环境下的这个锁叫作分布式锁。
5.1 原生 Zookeeper 实现 分布式锁案例
1) 分布式锁实现
package com.achang.lock2;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class DistributedLock {
private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
private int sessionTimeout = 2000;
private ZooKeeper zk;
private String rootNode = "locks";
private String subNode = "seq-";
private String waitPath;
private CountDownLatch connectLatch = new CountDownLatch(1);
private CountDownLatch waitLatch = new CountDownLatch(1);
private String currentNode;
public DistributedLock() throws IOException,InterruptedException, KeeperException {
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
connectLatch.countDown();
}
if (event.getType() == Event.EventType.NodeDeleted && event.getPath().equals(waitPath)){
waitLatch.countDown();
}
}
});
connectLatch.await();
Stat stat = zk.exists("/" + rootNode, false);
if (stat == null) {
System.out.println("根节点不存在");
zk.create("/" + rootNode, new byte[0],ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
}
public void zkLock() {
try {
currentNode = zk.create("/" + rootNode + "/" + subNode,null,ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
Thread.sleep(10);
List<String> childrenNodes = zk.getChildren("/" + rootNode, false);
if (childrenNodes.size() == 1) {
return;
} else {
Collections.sort(childrenNodes);
String thisNode = currentNode.substring(("/" + rootNode + "/").length());
int index = childrenNodes.indexOf(thisNode);
if (index == -1) {
System.out.println("数据异常");
} else if (index == 0) {
return;
} else {
this.waitPath = "/" + rootNode + "/" + childrenNodes.get(index - 1);
zk.getData(waitPath, true, new Stat());
waitLatch.await();
return;
}
}
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void zkUnlock() {
try {
zk.delete(this.currentNode, -1);
} catch (InterruptedException | KeeperException e) {
e.printStackTrace();
}
}
}
2)分布式锁 测试
package com.achang.lock2;
import org.apache.zookeeper.KeeperException;
import java.io.IOException;
public class DistributedLockTest {
public static void main(String[] args) throws
InterruptedException, IOException, KeeperException {
final DistributedLock lock1 = new DistributedLock();
final DistributedLock lock2 = new DistributedLock();
new Thread(new Runnable() {
@Override
public void run() {
try {
lock1.zkLock();
System.out.println("线程 1 获取锁");
Thread.sleep(5 * 1000);
lock1.zkUnlock();
System.out.println("线程 1 释放锁");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
lock2.zkLock();
System.out.println("线程 2 获取锁");
Thread.sleep(5 * 1000);
lock2.zkUnlock();
System.out.println("线程 2 释放锁");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
- 观察控制台变化
- 线程 1 获取锁
- 线程 1 释放锁
- 线程 2 获取锁
- 线程 2 释放锁
5.2Curator 框架 实现分布式锁案例
1)原生的 Java API 开发存在的问题
- (1)会话连接是异步的,需要自己去处理。比如使用 CountDownLatch
- (2)Watch 需要重复注册,不然就不能生效
- (3)开发的复杂性还是比较高的
- (4)不支持多节点删除和创建。需要自己去递归
2)Curator 是一个专门解决分布式锁的框架,解决了原生Java API
详情请查看官方文档:https://curator.apache.org/index.html
3 )Curator 案例实操
-
(1)添加依赖 <dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>4.3.0</version>
</dependency>
-
(2)代码实现 package com.achang.lock;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
public class CuratorLockTest {
private String rootNode = "/locks";
private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
private int connectionTimeout = 2000;
private int sessionTimeout = 2000;
public static void main(String[] args) {
new CuratorLockTest().test();
}
private void test() {
final InterProcessLock lock1 = new InterProcessMutex(getCuratorFramework(),rootNode);
final InterProcessLock lock2 = new InterProcessMutex(getCuratorFramework(),rootNode);
new Thread(new Runnable() {
@Override
public void run() {
try {
lock1.acquire();
System.out.println("线程 1 获取锁");
lock1.acquire();
System.out.println("线程 1 再次获取锁");
Thread.sleep(5 * 1000);
lock1.release();
System.out.println("线程 1 释放锁");
lock1.release();
System.out.println("线程 1 再次释放锁");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
lock2.acquire();
System.out.println("线程 2 获取锁");
lock2.acquire();
System.out.println("线程 2 再次获取锁");
Thread.sleep(5 * 1000);
lock2.release();
System.out.println("线程 2 释放锁");
lock2.release();
System.out.println("线程 2 再次释放锁");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public CuratorFramework getCuratorFramework (){
RetryPolicy policy = new ExponentialBackoffRetry(3000, 3);
CuratorFramework client =CuratorFrameworkFactory.builder()
.connectString(connectString)
.connectionTimeoutMs(connectionTimeout)
.sessionTimeoutMs(sessionTimeout)
.retryPolicy(policy).build();
client.start();
System.out.println("zookeeper 初始化完成...");
return client;
}
}
-
(2)观察控制台变化 线程 1 获取锁 线程 1 再次获取锁 线程 1 释放锁 线程 1 再次释放锁 线程 2 获取锁 线程 2 再次获取锁 线程 2 释放锁 线程 2 再次释放锁
企业面试真题(面试重点)
6.1 选举机制
半数机制,超过半数的投票通过,即通过。
-
(1)第一次启动选举规则: 投票过半数时,服务器 id 大的胜出 -
(2)第二次启动选举规则:
- ①EPOCH 大的直接胜出
- ②EPOCH 相同,事务 id 大的胜出
- ③事务 id 相同,服务器 id 大的胜出
6.2 生产 集群少 安装多少 zk 合适? ?
安装奇数 台。
- 生产经验:
- 10 台服务器:3 台 zk;
- 20 台服务器:5 台 zk;
- 100 台服务器:11 台 zk;
- 200 台服务器:11 台 zk
- 服务器台数多:好处,提高可靠性;坏处:提高通信延时
6.3 常用命令
ls、get、create、delete
|