Linux下使用ZMQ实践“请求-响应”异步服务器模型

一、背景

    上一篇文章《Linux下使用ZMQ实践“请求-响应”服务器模型》中使用的是REP-REQ套件,该套件的特点是必须一个请求对应一个响应,如果在应用中不想使用同步处理的方式呢?ZMQ有没有提供异步处理的方法?答案是使用DEALER-ROUTER套件。

    另外如何在多线程中安全传递消息的方法可以参见《Linux下使用ZMQ实践“生产者-消费者”模型》ZMQ_PULL、ZMQ_PUSH的实践。

二、相关知识

1、ZMQ_DEALER

       ZMQ_DEALER
           A socket of type ZMQ_DEALER is an advanced pattern used for extending request/reply sockets.
           Each message sent is round-robined among all connected peers, and each message received is
           fair-queued from all connected peers.

           When a ZMQ_DEALER socket enters the mute state due to having reached the high water mark for
           all peers, or if there are no peers at all, then any zmq_send(3) operations on the socket
           shall block until the mute state ends or at least one peer becomes available for sending;
           messages are not discarded.

           When a ZMQ_DEALER socket is connected to a ZMQ_REP socket each message sent must consist of
           an empty message part, the delimiter, followed by one or more body parts.

    DEALER是一种用于请求/答应模式的更高级的扩展Socket,它可以自由的收发消息,没有ZMQ_REP/ZMQ_REQ那样的限制。对于每一个连接,接收消息也是使用了公平队列,发送使用了循环队列(RR)。

    ZMQ_DEALER受ZMQ_RCVHW和ZMQ_SNDHW两个阀值影响(可通过zmq_setsockopt函数设置),一旦发送或接收队列达到阀值,Socket就会进入mute状态,此时对DEALER的任何zmq_send操作都会阻塞,直到mute状态结束。如果当前没有有效的连接,zmq_send操作也会阻塞,直到有新的连接到来为止。DEALER发生阻塞并不会丢弃消息。

    注意:如果ZMQ_DEALER连接到ZMQ_REP,每一个消息包必须包含一个空帧,然后再紧跟着数据包体。

2、ZMQ_ROUTER

    ZMQ_ROUTER           
           A socket of type ZMQ_ROUTER is an advanced socket type used for extending request/reply
           sockets. When receiving messages a ZMQ_ROUTER socket shall prepend a message part containing
           the routing id of the originating peer to the message before passing it to the application.
           Messages received are fair-queued from among all connected peers. When sending messages a
           ZMQ_ROUTER socket shall remove the first part of the message and use it to determine the
           routing id of the peer the message shall be routed to. If the peer does not exist anymore,
           or has never existed, the message shall be silently discarded. However, if
           ZMQ_R
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值