netty集群(一)-服務(wù)注冊發(fā)現(xiàn)

上篇文章介紹了如何搭建一個單機(jī)版本的netty聊天室:http://www.itdecent.cn/p/f786c70eeccc。

一、需要解決什么問題:

當(dāng)連接數(shù)超過單機(jī)的極限時,需要將netty服務(wù)擴(kuò)展成集群才能夠承載更多的連接數(shù),處理更多的消息。
在網(wǎng)上找了下似乎并沒有非常成熟標(biāo)準(zhǔn)的netty集群相關(guān)框架或中間件,于是我決定用zookeeper作為服務(wù)注冊中心來實現(xiàn)一個簡單的netty集群。

二、基于zookeeper做netty集群服務(wù)注冊發(fā)現(xiàn)的設(shè)計思路:

netty服務(wù)注冊發(fā)現(xiàn)流程

關(guān)鍵的幾個點(diǎn):
1.netty服務(wù)在啟動時,向zookeeper注冊一個臨時節(jié)點(diǎn),掛載在永久父節(jié)點(diǎn)/netty下,節(jié)點(diǎn)名是當(dāng)前節(jié)點(diǎn)的IP地址加端口,例如:192.168.1.1:7704。

2.和單點(diǎn)netty服務(wù)的區(qū)別是單點(diǎn)netty時客戶端建立鏈接的netty地址是寫死的,集群化后由注冊中心zookeeper管理可用netty服務(wù)清單,客戶端通過登錄接口去獲取可用netty服務(wù)地址,然后建立長連接。

3.當(dāng)長連接斷開時,重復(fù)上圖過程。

三、關(guān)鍵部分代碼

1.需要在netty應(yīng)用和接口應(yīng)用都引入下面三個工具類:

zookeeper發(fā)現(xiàn)節(jié)點(diǎn)工具類

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);
        }
    }
 
    /**
     * 通過服務(wù)發(fā)現(xiàn),獲取服務(wù)提供方的地址
     * @return
     */
    public String discover() {
        String data = null;
        int size = serviceAddressList.size();
        if (size > 0) {
            if (size == 1) {  //只有一個服務(wù)提供方
                data = serviceAddressList.get(0);
                logger.info("unique service address : {}", data);
            } else {          //使用隨機(jī)分配法。簡單的負(fù)載均衡法
                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;
    }
 
    /**
     * 獲取服務(wù)地址列表
     * @param zk
     */
    private void watchNode(final ZooKeeper zk) {
 
        try {
            //獲取子節(jié)點(diǎn)列表
            List<String> nodeList = zk.getChildren("/route", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (event.getType() == Event.EventType.NodeChildrenChanged) {
                        //發(fā)生子節(jié)點(diǎn)變化時再次調(diào)用此方法更新服務(wù)地址
                        watchNode(zk);
                    }
                }
            });
            logger.info("node data: {}", nodeList);
            this.serviceAddressList = nodeList;
        } catch (KeeperException | InterruptedException e) {
            logger.error("", e);
        }
    }
}

zookeeper注冊節(jié)點(diǎn)工具類

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 服務(wù)器
     * @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;
    }
    
    /**
     * 創(chuàng)建頂級節(jié)點(diǎn)
     * @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("創(chuàng)建路由根節(jié)點(diǎn) ({})", path);
            }
        } catch (KeeperException | InterruptedException e) {
            logger.error("創(chuàng)建路由根節(jié)點(diǎn)異常:", e);
        }
    }

    /**
     * 創(chuàng)建子節(jié)點(diǎn)
     * @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("創(chuàng)建節(jié)點(diǎn) ({} => {})", path, data);
            }
        } catch (KeeperException | InterruptedException e) {
            logger.error("創(chuàng)建節(jié)點(diǎn)異常:", e);
        }
    }
    
}

測試服務(wù)注冊發(fā)現(xiàn)工具類:

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";
        // 將本機(jī)netty服務(wù)實例注冊到zookeeper
        ServiceRegistry serviceRegistry = new ServiceRegistry(registryAddress);
        
        // 獲取本機(jī)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次服務(wù)命中情況:");
        for (Map.Entry<String, Integer> entry : routeMap.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }
    

}

2.netty應(yīng)用引入上面三個工具類,啟動時向zookeeper注冊自己的代碼如下,在netty服務(wù)啟動時調(diào)用:
    /**
     * 向注冊中心注冊自己
     * @throws UnknownHostException 
     */
    public static void registerZK() throws UnknownHostException {
        // 獲取本機(jī)ip
        String ip = InetAddress.getLocalHost().getHostAddress();
        // 獲取zookeeper注冊地址
        String registeyAddress = PropKit.use("zookeeper.properties").get("zk_registry_address");
        // 將本機(jī)netty服務(wù)實例注冊到zookeeper,以ip加端口作為znode名,掛載到父節(jié)點(diǎn)下面,成為可用服務(wù)實例列表
        ServiceRegistry serviceRegistry = new ServiceRegistry(registeyAddress);
        serviceRegistry.register(ip + ":" + WebSocketConstant.WEB_SOCKET_PORT);
    }

3.接口服務(wù)引入三個工具類-獲取可用netty服務(wù)地址代碼示例如下:

    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.點(diǎn)對點(diǎn)發(fā)送消息,如何知道這條消息存在哪個netty服務(wù)節(jié)點(diǎn),需要通知哪個服務(wù)節(jié)點(diǎn)推送消息。
2.對群成員廣播消息時,如何知道這個群的成員分布在哪些netty服務(wù)節(jié)點(diǎn)上。

下篇博文描述消息的路由和推送

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容