1. 程式人生 > >zeroMQ 簡單的PUB-SUB 高效能模式,java 語言版本

zeroMQ 簡單的PUB-SUB 高效能模式,java 語言版本

package com.firebird.server;


import java.util.ArrayList;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Socket;
import org.zeromq.ZMsg;


public class PubSubPattern {
public static class PublisherRunnable implements Runnable{
@Override
public void run(){
ZContext cxt = new ZContext(1);
Socket hwServer = cxt.createSocket(ZMQ.PUB);
hwServer.bind("tcp://*:5550");

while(!Thread.currentThread().isInterrupted()){
ZMsg sendMsg = new ZMsg();
sendMsg.addString("world");
sendMsg.send(hwServer);
sendMsg.destroy();
}

hwServer.close();
cxt.destroy();
}
}

public static class SubcriberRunnable implements Runnable{

@Override
public void run(){
ZContext cxt = new ZContext(1);
Socket hwSocket = cxt.createSocket(ZMQ.SUB);
hwSocket.connect("tcp://*:5550");

//長度為0的byte陣列,說明接受所有到達的訊息,這兩行程式碼是一定要加的,不然會接受不到資料,
byte[] filter = new byte[0];
hwSocket.subscribe(filter);

while(!Thread.currentThread().isInterrupted()){
ZMsg msg = ZMsg.recvMsg(hwSocket, 0);
if(msg == null){
continue;
}

System.out.println(msg.toString());
msg.destroy();
}

hwSocket.close();
cxt.destroy();
}
}

public static void main(String[] args) {



Thread bossThread = new Thread(new PublisherRunnable());
bossThread.start();

ArrayList<Thread> thArray = new ArrayList<Thread>(5);
for(int i = 0 ;i< 5;i++){
Thread th = new Thread(new SubcriberRunnable());
thArray.add(th);
th.start();
}

/*
try{
Thread.sleep(1000);

for(int i = 0;i<thArray.size();i++){
thArray.get(i).interrupt();
}

bossThread.interrupt();
}catch(Exception e){
e.printStackTrace();
}*/
}
}