Zookeeper实现负载均衡原理

Zookeeper实现负载均衡原理

先玩个正常的,好玩的socket编程:

服务端:

首先公共的这个Handler:

package com.toov5.zkDubbo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerHandler implements Runnable {
    private Socket socket;

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }

    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 = null;
            while (true) {
                body = in.readLine();
                if (body == null)
                    break;
                System.out.println("Receive : " + body);
                out.println("Hello, " + 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;
            }
        }
    }
}

 

package com.toov5.zkDubbo;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.I0Itec.zkclient.ZkClient;

//##ServerScoekt服务端
public class ZkServerScoekt implements Runnable {
    private static int port = 18080;  //socket 服务启动后的所使用的 端口号

    public static void main(String[] args) throws IOException {
        ZkServerScoekt server = new ZkServerScoekt(port);  //构造函数传入port
    //    regServer();  //去zk注册
        Thread thread = new Thread(server);
        thread.start();
    }

    public ZkServerScoekt(int port) {
        this.port = port;
    }
//  //注册服务
//    public static void regServer(){
//        //1、建立zk连接
//    ZkClient zkClient = new ZkClient("192.168.91.5",5000,10000);
//        //2.先创建父节点
//    String root = "/toov5";
//    if (!zkClient.exists(root)) {
//        //如果父节点不存,直接创建父节点
//        zkClient.createPersistent(root);  //持久节点
//    }
//       //3、创建子节点
//     String nodeName = root+"/service_"+port;      
//     String nodeValue="127.0.0.1:"+port;
//     if (zkClient.exists(nodeName)) {  //如果存在 直接删除掉
//        zkClient.delete(nodeName);
//    }
//     zkClient.createEphemeral(nodeName); //字节的 临时节点  如果服务宕机了 找不到了就
//     System.out.println("服务注册成功"+nodeName);
//     
//    }
//    
//    
    
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("Server start port:" + port);
            Socket socket = null;
            while (true) {
                socket = serverSocket.accept();
                new Thread(new ServerHandler(socket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (Exception e2) {

            }
        }
    }

}

客户端:

package com.toov5.zkDubbo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ZkServerClient {
    public static List listServer = new ArrayList();

    public static void main(String[] args) {
        initServer();
        ZkServerClient     client= new ZkServerClient();
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String name;
            try {
                name = console.readLine();
                if ("exit".equals(name)) {
                    System.exit(0);
                }
                client.send(name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 注册所有server 
    public static void initServer() {
        listServer.clear();
        listServer.add("127.0.0.1:18080"); //连接服务 放到list中   存放集群地址 做负载均衡用的
    }

    // 获取当前server信息
    public static String getServer() {
        return listServer.get(0);
    }
    
    public void send(String name) {

        String server = ZkServerClient.getServer();
        String[] cfg = server.split(":"); 

        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            socket = new Socket(cfg[0], Integer.parseInt(cfg[1]));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            out.println(name);
            while (true) {
                String resp = in.readLine();
                if (resp == null)
                    break;
                else if (resp.length() > 0) {
                    System.out.println("Receive : " + resp);
                    break;
                }
            }
        } 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();
                }
            }
        }
    }
}

运行结果:

Zookeeper实现负载均衡原理_第1张图片

 

引申思路

使用Zookeeper实现负载均衡原理,服务器端将启动的服务注册到,zk注册中心上,采用临时节点。客户端从zk节点上获取最新服务节点信息,本地使用负载均衡算法,随机分配服务器。

 

Zookeeper实现负载均衡原理_第2张图片

1、会员服务 项目启动时候 会在zk上面创建临时节点  /toov5 对应的value是127.0.0.1   

       如果是集群  /toov5 下面会会以 节点形式存储 节点名字就是IP+端口    value 分别也是 IP+端口   有些是没有用到value的哦  

2、订单直接去使用 /toov5 查询下面的子节点信息,获取到之后。在本地使用负载均衡算法实现调用,决定使用哪个。   

      127.0.0.1:8080 

      127.0.0.1:8081      

 

PS: 任何服务的底层都是 socke 技术

 

 socket客户端 ( 客户端去获取注册信息)                                                          socket服务器端

 

废话不多说,项目:

          
		
			com.101tec
			zkclient
			0.8
		
	  

  这个不是Apache的哦注意         

 服务端代码:

package com.toov5.zkDubbo;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.I0Itec.zkclient.ZkClient;

//##ServerScoekt服务端
public class ZkServerScoekt implements Runnable {
    private static int port = 18081;  //socket 服务启动后的所使用的 端口号

    public static void main(String[] args) throws IOException {
        ZkServerScoekt server = new ZkServerScoekt(port);  //构造函数传入port
        regServer();  //去zk注册
        Thread thread = new Thread(server);
        thread.start();
    }

    public ZkServerScoekt(int port) {
        this.port = port;
    }
  //注册服务
    public static void regServer(){
        //1、建立zk连接
    ZkClient zkClient = new ZkClient("192.168.91.5",5000,10000);
        //2.先创建父节点
    String root = "/toov5";
    if (!zkClient.exists(root)) {
        //如果父节点不存,直接创建父节点
        zkClient.createPersistent(root);  //持久节点
    }
       //3、创建子节点
     String nodeName = root+"/service_"+port;      
     String nodeValue="127.0.0.1:"+port;
     if (zkClient.exists(nodeName)) {  //如果存在 直接删除掉
        zkClient.delete(nodeName);
    }
     zkClient.createEphemeral(nodeName); //字节的 临时节点  如果服务宕机了 找不到了就
     System.out.println("服务注册成功"+nodeName);
     
    }
    
    
    
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("Server start port:" + port);
            Socket socket = null;
            while (true) {
                socket = serverSocket.accept();
                new Thread(new ServerHandler(socket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (Exception e2) {

            }
        }
    }

}

客户端代码:

package com.toov5.zkDubbo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ZkServerClient {
    public static List listServer = new ArrayList();

    public static void main(String[] args) {
        initServer();
        ZkServerClient     client= new ZkServerClient();
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String name;
            try {
                name = console.readLine();
                if ("exit".equals(name)) {
                    System.exit(0);
                }
                client.send(name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 注册所有server 
    public static void initServer() {
        listServer.clear();
        listServer.add("127.0.0.1:18080"); //连接服务 放到list中   存放集群地址 做负载均衡用的
    }

    // 获取当前server信息
    public static String getServer() {
        return listServer.get(0);
    }
    
    public void send(String name) {

        String server = ZkServerClient.getServer();
        String[] cfg = server.split(":"); 

        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            socket = new Socket(cfg[0], Integer.parseInt(cfg[1]));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            out.println(name);
            while (true) {
                String resp = in.readLine();
                if (resp == null)
                    break;
                else if (resp.length() > 0) {
                    System.out.println("Receive : " + resp);
                    break;
                }
            }
        } 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();
                }
            }
        }
    }
}

 

Zookeeper实现负载均衡原理_第3张图片

启动服务端后的结果:

可以看到 去zk注册了信息。服务的名字 和子节点 

 其中子节点是 临时节点 相当于如果服务宕机了 就查不到了哦

Zookeeper实现负载均衡原理_第4张图片

 

启动三次服务端后:

Zookeeper实现负载均衡原理_第5张图片

 

 然后 去zk读取节点信息:

客户端  负载均衡轮训算法   

请求次数 %  服务端数 = 服务器端口号的奇数偶数

客户端:

package com.toov5.zkDubbo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.I0Itec.zkclient.ZkClient;

public class ZkServerClient {
    public static List listServer = new ArrayList();

    public static void main(String[] args) {
        initServer();
        ZkServerClient     client= new ZkServerClient();
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String name;
            try {
                name = console.readLine();
                if ("exit".equals(name)) {
                    System.exit(0);
                }
                client.send(name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 注册所有server 
    public static void initServer() {
        listServer.clear();
//        listServer.add("127.0.0.1:18080"); //连接服务 放到list中   存放集群地址 做负载均衡用的   
        //建立zk连接
        ZkClient zkClient = new ZkClient("192.168.91.5",5000,10000);
        //读取父节点信息
        String root = "/toov5";
        List children=zkClient.getChildren(root);
        for(String pString : children){
            //父+子 =完整的路径
            String path = root+"/"+pString;
            String nodeValue =zkClient.readData(path);
            //把值放到集合中去
            listServer.add(nodeValue);
        }
        //服务发现成功
         System.out.println("服务发现:"+listServer.toString());
         //然后给 serverCount赋值
         serverCount=listServer.size();
         
    }
 
  //请求总数
    private static  int  reqCount = 1;
  //服务个数    
    private static int  serverCount = 0; //初始值是0
    
    // 获取当前server信息
    public static String getServer() {
//        return listServer.get(0);  不能写死  本地负载均衡轮询算法
    String serverName = listServer.get(reqCount%serverCount );
    System.out.println("客户端请求次数:"+reqCount+"对应服务器"+serverName);
    reqCount++;
    return serverName;    
    }
    
    public void send(String name) {

        String server = ZkServerClient.getServer();
        String[] cfg = server.split(":"); 

        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            socket = new Socket(cfg[0], Integer.parseInt(cfg[1]));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            out.println(name);
            while (true) {
                String resp = in.readLine();
                if (resp == null)
                    break;
                else if (resp.length() > 0) {
                    System.out.println("Receive : " + resp);
                    break;
                }
            }
        } 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();
                }
            }
        }
    }
}

启动后(后端服务启动三个):

 

访问一次:取模算法后的结果

Zookeeper实现负载均衡原理_第6张图片

第二次、第三次:

Zookeeper实现负载均衡原理_第7张图片

 

 看到结果 太美妙了!

美妙集中在此:

Zookeeper实现负载均衡原理_第8张图片

 

好好欣赏下~~

 

 

你可能感兴趣的:(负载均衡,Zookeeper)