PUB/SUB模式: 发布/订阅模式。该模式是单向的,发布者send msg, 订阅者receive msg. 一旦有消息发出,pub会发送给所有的sub。.
模式如下图:
可以看出发布者绑定绑定一个端口,订阅者通过连接发布者接受订阅的消息。
官网描述这种模式要注意以下几点:
1. pub/sub模式下,sub事实上可以连接多个pub,每次只连接一个connect,所以接收到的消息可以是叫错的,以至于不会单个pub掩盖了其他pub
2. 如果存在某个pub没有被任何sub连接,则该pub会丢弃所有的消息
3. 如果你采用tcp的连接方式,sub很慢,消息将会堆积在pub,后期会对该问题有个较好的解决
4. 目前的而版本,过滤发生在sub端,而不是pub端,意思就是说一个pub会发送所有的消息到所有的sub, 由sub决定是要drop这个msg.
以下代码显示一个pub 两个sub, Publisher发送两种主题的消息A和B, Sub1接受B主题的消息, Sub2接受A主题的消息。
package pubsub;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Context;
import org.zeromq.ZMQ.Socket;
public class Publisher {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Context context = ZMQ.context(1);
Socket publisher = context.socket(ZMQ.PUB);
publisher.bind("tcp://*:5557");
int i = 0;
while (true) {
Thread.currentThread().sleep(1000);
publisher.send("A".getBytes(), ZMQ.SNDMORE);
publisher.send("This is A".getBytes(), 0);
publisher.send("B".getBytes(), ZMQ.SNDMORE);
publisher.send("This is B".getBytes(), 0);
}
}
}
package pubsub;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Context;
import org.zeromq.ZMQ.Socket;
public class Sub1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Context context = ZMQ.context(1);
Socket subscribe = context.socket(ZMQ.SUB);
subscribe.connect("tcp://127.0.0.1:5557");
subscribe.subscribe("B".getBytes());
while (true) {
System.out.println(new String(subscribe.recv(0)));
System.out.println(new String(subscribe.recv(0)));
}
}
}
package pubsub;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Context;
import org.zeromq.ZMQ.Socket;
public class Sub2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Context context = ZMQ.context(1);
Socket subscribe = context.socket(ZMQ.SUB);
subscribe.connect("tcp://127.0.0.1:5557");
//subscribe.subscribe("topic".getBytes());
subscribe.subscribe("A".getBytes());
while (true) {
System.out.println(new String(subscribe.recv(0)));
System.out.println(new String(subscribe.recv(0)));
}
}
}
结果显示
Sub1:
B
This is B
B
This is B
B
This is B
B
This is B
...
Sub2:
A
This is A
A
This is A
A
This is A
A
This is A