**欢迎关注公众号**
**微信扫一扫**
  • 思路
    使用Zookeeper实现负载均衡原理的演示。演示服务端和客户端通信。当只有一个服务端时,客户端把消息直接发给该服务端;当有多个服务端运行时(端口不同),客户端实现均衡地选择服务端来提供服务。客户端根据请求次数依次选择不同的服务端来连接,达到“负载均衡”的效果。服务端每次启动将服务注册到zk注册中心上,采用临时节点。客户端监听zk注册中心指定的路径,从zk节点上获取最新服务节点信息,模拟简单的负载均衡算法,轮流分配服务器。

#创建项目工程

引入Maven依赖
<dependencies>
	<dependency>
		<groupId>com.101tec</groupId>
		<artifactId>zkclient</artifactId>
		<version>0.8</version>
	</dependency>
</dependencies>
创建Server服务端
  • MyZkServer
public class MyZkServer implements Runnable {
    private int port;
    public MyZkServer(int port) {
        this.port = port;
    }
    /**
     * 向ZooKeeper注册当前服务端 
     */
    public void registerToZk() {
        ZkClient client = new ZkClient("127.0.0.1:2181", 12000, 12000);
        String path = "/hellozk/server" + port;
        if (client.exists(path)) {
            client.delete(path);
        }
        client.createEphemeral(path, "127.0.0.1:" + port);
    }
    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            registerToZk();
            System.out.println("Server started,ip: " + serverSocket.getInetAddress() + " port:" + port);
            Socket socket;
            //保持服务器端程序一直运行
            while (true) {
                System.out.println("============"+serverSocket+"等待连接============");
                socket = serverSocket.accept();
                //单开一个线程处理每一个客户端连接
                Thread thread=new Thread(new MyServerHandler(socket));
                thread.start();
                System.out.println("============"+thread+"启动处理请求============");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (Exception e2) {
            }
        }
    }
    public static void main(String[] args) throws IOException {
        int port = 1003;
        MyZkServer server = new MyZkServer(port);
        Thread thread = new Thread(server);
        thread.start();
    }
}
创建Client客戶端
  • MyZkClient
/**
 * 客户端均衡地调用服务端,基于zookeeper实现
 */
public class MyZkClient {
    /**
     * 客户端保存所有可用服务端信息
     */
    public static List<String> serverList = new ArrayList<String>();
    /**
     * 请求计数器
     */
    private static int reqestCount = 0;
    /**
     * 客户端扫描所有的server
     */
    public static void initServer() {
        String path = "/hellozk";
        final ZkClient zkClient = new ZkClient("127.0.0.1:2181", 12000, 12000);
        List<String> children = zkClient.getChildren(path);
        System.out.println(children);
        for (String serverIp : children) {
            System.out.println(serverIp+"==============serverIp==============");
            serverList.add((String) zkClient.readData(path + "/" + serverIp));
        }
        System.out.println("####从zookeeper注册中心获取的服务器server信息==>serverList:" + serverList.toString());
        // 监听事件
        zkClient.subscribeChildChanges(path, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                serverList.clear();
                for (String serverIp : currentChilds) {
                    System.out.println(serverIp+"==============serverIp==============");
                    serverList.add((String)zkClient.readData(parentPath + "/" + serverIp));
                }
                System.out.println("####客户端监听到节点发生变化###服务器server信息==>serverList:" + serverList.toString());

            }
        });
    }
    /**
     * 简单的负载均衡实现(按照请求计数来分配server)
     */
    public static String getServer() {
        int serverCount = serverList.size();
        String serverHost = serverList.get(reqestCount % serverCount);
        reqestCount++;
        return serverHost;
    }
    public void send(String name) {
        String server = MyZkClient.getServer();
        System.out.println("reqestCount:" + reqestCount);
        System.out.println("获取到的server:" + server);
        String[] config = server.split(":");
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            socket = new Socket(config[0], Integer.parseInt(config[1]));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            out.println(name);
            String resp = in.readLine();
            System.out.println("client receive : " + resp);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        initServer();
        MyZkClient client = new MyZkClient();
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String name;
            try {
                System.out.println("=========请输入=========");
                name = console.readLine();
                if ("exit".equals(name)) {
                    System.exit(0);
                }
                client.send(name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Server端请求处理器
  • ServerHandler
public class MyServerHandler implements Runnable {
    private Socket socket;
    public MyServerHandler(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);
            String body;
            while ((body = in.readLine()) != null) {
                System.out.println("server receive : " + body);
                out.println("Hello,I am Server~, " + body);
            }
        } catch (Exception e) {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                out.close();
            }
            if (this.socket != null) {
                try {
                    this.socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                //this.socket = null;
            }
        }
    }
}

上述程序简单模拟了zk的使用场景之-实现负载均衡~

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐