1. 程式人生 > >Dubbo動態負載均衡(socket環境實現)

Dubbo動態負載均衡(socket環境實現)

消費者 去註冊中心獲取資訊 然後快取到本地 如果有生產者某個服務宕機了  會通過通知的方式告知 (訂閱的方式)

 

微服務rpc遠端呼叫框架中,服務的負載均衡都是採用本地負載均衡的,Spring Cloud  使用的ribbon(本地負載均衡)

 如果使用Nginx,那麼獲取到服務資訊後,請求要交給Nginx,再由Nginx進行轉發實現負載均衡

本地負載均衡:本地服務從註冊中心上獲取服務資訊列表(快取在JVM),然後在本地使用rpc遠端呼叫技術,比如Netty、Netty。本地負載均衡更容易實時重新整理新資料。

本地效率更高呀

 實現如下架構:

 

 在玩的時候注意 不要加埠號

完整路徑:/ 一定要加  

 

pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.toov5.SocketForDubbo</groupId>
  <artifactId>com.toov5.SocketForDubbo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
    <dependencies>
    <dependency>
        <groupId>com.101tec</groupId>
        <artifactId>zkclient</artifactId>
        <version>0.8</version>
    </dependency>
</dependencies>
</project>

 伺服器端

package com.toov5.SocketForDubboServer;

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 = 8080; // socket 服務啟動後的所使用的 埠號
    private
static String parentService = "/service"; private static ZkClient zkClient = new ZkClient("192.168.91.5"); 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) { ZkServerScoekt.port = port; } // 註冊服務 public static void regServer() { // 先建立父節點 判斷 if (!zkClient.exists(parentService)) { // 建立父 節點 zkClient.createPersistent(parentService); // 建立父節點(持久化) } //存在就不用管了 // 建立子節點 String serverKey = parentService + "/server_" + port; // 約定了個規範 if (!zkClient.exists(serverKey)) { zkClient.createEphemeral(serverKey, "127.0.0.1:" + port); // 臨時的 上面的刪除是必須的 刪除一遍 在建立 保持最新的 本地獲取到 進行負載均衡 } else { zkClient.delete(serverKey); } } 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.SocketForDubboServer;

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.SocketForDubboClient;

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 javax.mail.Address;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.data.Stat;
import org.jboss.netty.channel.StaticChannelPipeline;
import org.jboss.netty.util.internal.SystemPropertyUtil;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.w3c.dom.ls.LSInput;

public class ZkServerClient {
    public static List<String> listServer = new ArrayList<String>();
    private static ZkClient zkClient = new ZkClient("192.168.91.5");
    private static String parentService = "/service";

    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() {
        // 讀取所有節點 資訊
    List<String> children = zkClient.getChildren(parentService);
    getChildren(zkClient, children);    
    zkClient.subscribeChildChanges(parentService, new IZkChildListener() {
        public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
            System.out.println("註冊中心服務列表資訊有變化"); 
            getChildren(zkClient, currentChilds);//如果監聽到有變化了 就要重新讀取哦
        }
    });    
        
    }
  
 public static    void getChildren(ZkClient zkClient, List<String> children) {
     listServer.clear();
    for (String ch : children) {
        String serverAddr = zkClient.readData(parentService + "/" + ch); // 拿到服務地址
        listServer.add(serverAddr);
    }
    System.out.println("服務介面地址"+listServer.toString()); 
}
    
    
    // 請求總數
    private static int reqCount = 1;
//  //服務個數    
//    private static int  serverCount = 0; //初始值是0

    // 獲取當前server資訊
    public static String getServer() {
        int index = reqCount % listServer.size();
        String address = listServer.get(index);
        System.out.println("客戶端請求伺服器" + address);
        reqCount++;
        return address;
    }

    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();
                }
            }
        }
    }
}

 

 

客戶端去獲取下面的 地址資訊 就好辦了:

 

 執行結果

 動態的哦