上篇文章介紹瞭如何搭建一個單機版本的netty聊天室:https://www.jianshu.com/p/f786c70eeccc。
一、需要解決什麼問題:
當連線數超過單機的極限時,需要將netty服務擴充套件成叢集才能夠承載更多的連線數,處理更多的訊息。
在網上找了下似乎並沒有非常成熟標準的netty叢集相關框架或中介軟體,於是我決定用zookeeper作為服務註冊中心來實現一個簡單的netty叢集。
二、基於zookeeper做netty叢集服務註冊發現的設計思路:
關鍵的幾個點:
1.netty服務在啟動時,向zookeeper註冊一個臨時節點,掛載在永久父節點/netty下,節點名是當前節點的IP地址加埠,例如:192.168.1.1:7704。
2.和單點netty服務的區別是單點netty時客戶端建立連結的netty地址是寫死的,叢集化後由註冊中心zookeeper管理可用netty服務清單,客戶端通過登入介面去獲取可用netty服務地址,然後建立長連線。
3.當長連線斷開時,重複上圖過程。
三、關鍵部分程式碼
1.需要在netty應用和介面應用都引入下面三個工具類:
zookeeper發現節點工具類
package com.msgcenter.util.zookeeper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServiceDiscovery {
private static final Logger logger = LoggerFactory.getLogger(ServiceDiscovery.class);
private CountDownLatch latch = new CountDownLatch(1);
private volatile List<String> serviceAddressList = new ArrayList<>();
private String registryAddress; // 註冊中心的地址
public ServiceDiscovery(String registryAddress) {
this.registryAddress = registryAddress;
ZooKeeper zk = connectServer();
if (zk != null) {
watchNode(zk);
}
}
/**
* 通過服務發現,獲取服務提供方的地址
* @return
*/
public String discover() {
String data = null;
int size = serviceAddressList.size();
if (size > 0) {
if (size == 1) { //只有一個服務提供方
data = serviceAddressList.get(0);
logger.info("unique service address : {}", data);
} else { //使用隨機分配法。簡單的負載均衡法
data = serviceAddressList.get(ThreadLocalRandom.current().nextInt(size));
logger.info("choose an address : {}", data);
}
}
return data;
}
/**
* 連線 zookeeper
* @return
*/
private ZooKeeper connectServer() {
ZooKeeper zk = null;
try {
zk = new ZooKeeper(registryAddress, 2000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
latch.countDown();
}
}
});
latch.await();
} catch (IOException | InterruptedException e) {
logger.error("", e);
}
return zk;
}
/**
* 獲取服務地址列表
* @param zk
*/
private void watchNode(final ZooKeeper zk) {
try {
//獲取子節點列表
List<String> nodeList = zk.getChildren("/route", new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeChildrenChanged) {
//發生子節點變化時再次呼叫此方法更新服務地址
watchNode(zk);
}
}
});
logger.info("node data: {}", nodeList);
this.serviceAddressList = nodeList;
} catch (KeeperException | InterruptedException e) {
logger.error("", e);
}
}
}
zookeeper註冊節點工具類
package com.msgcenter.util.zookeeper;
import java.util.concurrent.CountDownLatch;
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;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServiceRegistry {
private static final Logger logger = LoggerFactory.getLogger(ServiceRegistry.class);
private static final String ROOT_NODE = "/route";
private CountDownLatch latch = new CountDownLatch(1);
private String registryAddress;
public ServiceRegistry(String registryAddress) {
this.registryAddress = registryAddress;
}
public void register(String childNode) {
if (childNode != null) {
ZooKeeper zk = connectServer();
if (zk != null) {
try {
if (null == zk.exists(ROOT_NODE, false)) {
createRootNode(zk);
}
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
createNode(zk, childNode);
}
}
}
/**
* 連線 zookeeper 伺服器
* @return
*/
private ZooKeeper connectServer() {
ZooKeeper zk = null;
try {
zk = new ZooKeeper(registryAddress, 2000, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
latch.countDown();
}
}
});
latch.await();
} catch (Exception e) {
logger.error("", e);
}
return zk;
}
/**
* 建立頂級節點
* @param zk
* @param data
*/
private void createRootNode(ZooKeeper zk) {
try {
if (null == zk.exists(ROOT_NODE, false)) {
String path = zk.create(ROOT_NODE, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
logger.info("建立路由根節點 ({})", path);
}
} catch (KeeperException | InterruptedException e) {
logger.error("建立路由根節點異常:", e);
}
}
/**
* 建立子節點
* @param zk
* @param data
*/
private void createNode(ZooKeeper zk, String data) {
try {
String node = ROOT_NODE + "/" + data;
if (null == zk.exists(node, false)) {
byte[] bytes = data.getBytes();
String path = zk.create(node, bytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
logger.info("建立節點 ({} => {})", path, data);
}
} catch (KeeperException | InterruptedException e) {
logger.error("建立節點異常:", e);
}
}
}
測試服務註冊發現工具類:
package com.msgcenter.util.zookeeper;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import com.msgcenter.constant.WebSocketConstant;
public class ZookeeperTester {
public static void main(String[] args) throws UnknownHostException, InterruptedException {
// 獲取zookeeper註冊地址
String registryAddress = "47.106.99.2:2181";
// 將本機netty服務例項註冊到zookeeper
ServiceRegistry serviceRegistry = new ServiceRegistry(registryAddress);
// 獲取本機ip
// String ip = InetAddress.getLocalHost().getHostAddress();
String ip1 = "192.168.1.1";
String ip2 = "192.168.1.2";
String ip3 = "192.168.1.3";
serviceRegistry.register(ip1 + ":" + WebSocketConstant.WEB_SOCKET_PORT);
serviceRegistry.register(ip2 + ":" + WebSocketConstant.WEB_SOCKET_PORT);
serviceRegistry.register(ip3 + ":" + WebSocketConstant.WEB_SOCKET_PORT);
ServiceDiscovery serviceDiscovery = new ServiceDiscovery(registryAddress);
Map<String, Integer> routeMap = new HashMap<String, Integer>();
for (int i = 0; i < 10; i++) {
String address = serviceDiscovery.discover();
if (!routeMap.containsKey(address)) {
routeMap.put(address, 0);
}
routeMap.put(address, routeMap.get(address) + 1);
}
System.out.println("獲取10次服務命中情況:");
for (Map.Entry<String, Integer> entry : routeMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
2.netty應用引入上面三個工具類,啟動時向zookeeper註冊自己的程式碼如下,在netty服務啟動時呼叫:
/**
* 向註冊中心註冊自己
* @throws UnknownHostException
*/
public static void registerZK() throws UnknownHostException {
// 獲取本機ip
String ip = InetAddress.getLocalHost().getHostAddress();
// 獲取zookeeper註冊地址
String registeyAddress = PropKit.use("zookeeper.properties").get("zk_registry_address");
// 將本機netty服務例項註冊到zookeeper,以ip加埠作為znode名,掛載到父節點下面,成為可用服務例項列表
ServiceRegistry serviceRegistry = new ServiceRegistry(registeyAddress);
serviceRegistry.register(ip + ":" + WebSocketConstant.WEB_SOCKET_PORT);
}
3.介面服務引入三個工具類-獲取可用netty服務地址程式碼示例如下:
public ResponseResult<String> getNettyServer() {
String discoveryAddress = "47.106.99.2:2181";
ServiceDiscovery serviceDiscovery = new ServiceDiscovery(discoveryAddress);
String address = serviceDiscovery.discover();
return new ResponseResult<String>(address);
}
上述步驟解決了建立連線路由的問題,下一步還需要解決訊息的路由問題:
1.點對點傳送訊息,如何知道這條訊息存在哪個netty服務節點,需要通知哪個服務節點推送訊息。
2.對群成員廣播訊息時,如何知道這個群的成員分佈在哪些netty服務節點上。
下篇博文描述訊息的路由和推送