1. 程式人生 > >ZeroMQ之模式 請求迴應模型(Request-Reply)

ZeroMQ之模式 請求迴應模型(Request-Reply)

一、前言

ZeroMQ將訊息通訊分成4種模型,分別是一對一結對模型(Exclusive-Pair)、請求迴應模型(Request-Reply)、釋出訂閱模型(Publish-Subscribe)、推拉模型(Push-Pull)。這4種模型總結出了通用的網路通訊模型,在實際中可以根據應用需要,組合其中的2種或多種模型來形成自己的解決方案。

二、ZeroMQ之Hello World

一個簡單的請求應答模型

特點:1:1訊息通訊模型,可以認為是一個TCP Connection ,但TCP Server只能接受一個連線,資料可以又向流動。



Server:

//
//  Hello World server in Java
//  Binds REP socket to tcp://*:5555
//  Expects "Hello" from client, replies with "World"
//

import org.zeromq.ZMQ;

public class hwserver {

    public static void main(String[] args) throws Exception {
        ZMQ.Context context = ZMQ.context(1);

        //  Socket to talk to clients
        ZMQ.Socket responder = context.socket(ZMQ.REP);
        responder.bind("tcp://*:5555");

        while (!Thread.currentThread().isInterrupted()) {
            // Wait for next request from the client
            byte[] request = responder.recv(0);
            System.out.println("Received Hello");

            // Do some 'work'
            Thread.sleep(1000);

            // Send reply back to client
            String reply = "World";
            responder.send(reply.getBytes(), 0);
        }
        responder.close();
        context.term();
    }
}

Client:
//
//  Hello World client in Java
//  Connects REQ socket to tcp://localhost:5555
//  Sends "Hello" to server, expects "World" back
//

import org.zeromq.ZMQ;

public class hwclient {

    public static void main(String[] args) {
        ZMQ.Context context = ZMQ.context(1);

        //  Socket to talk to server
        System.out.println("Connecting to hello world server...");

        ZMQ.Socket requester = context.socket(ZMQ.REQ);
        requester.connect("tcp://localhost:5555");

        for (int requestNbr = 0; requestNbr != 10; requestNbr++) {
            String request = "Hello";
            System.out.println("Sending Hello " + requestNbr);
            requester.send(request.getBytes(), 0);

            byte[] reply = requester.recv(0);
            System.out.println("Received " + new String(reply) + " " + requestNbr);
        }
        requester.close();
        context.term();
    }
}

在幕後發生了很多事,但是我們程式設計師關心的是程式碼是否簡短和令人滿意,甚至在重荷下它是否也不會經常崩潰掉。這是請求-應答模型,可能是0MQ中最簡單的模型。它主要用於遠端過程呼叫和典型的客戶-伺服器模式。