上篇文章介绍了如何搭建一个单机版本的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服务节点上。
下篇博文描述消息的路由和推送