zeromq/jzmq pub/sub發布訂閱java代碼

來源:互聯網
上載者:User

引用:http://iyuan.iteye.com/blog/973013

這裡的發布與訂閱角色是絕對的,即發行者無法使用recv,訂閱者不能使用send,並且訂閱者需要設定訂閱條件"setsockopt"。 

按照官網的說法,在這種模式下很可能發行者剛啟動時發布的資料出現丟失,原因是用zmq發送速度太快,在訂閱者尚未與發行者建立聯絡時,已經開始了資料發布(內部區域網路沒這麼誇張的)。官網給了兩個解決方案;1,發行者sleep一會再發送資料(這個被標註成愚蠢的);2,(還沒有看到那,在後續中發現的話會更新這裡)。 


 上代碼:發布端:
package com.zeromq.test.Sync_pub_sub;import org.zeromq.ZMQ;import org.zeromq.ZMQ.Context;import org.zeromq.ZMQ.Socket;/** * @author 呂桂強 * @email larry.lv.word@gmail.com * @version 建立時間:2012-4-26 下午8:17:40 */public class syncpub{//等待10個訂閱者protected static int SUBSCRIBERS_EXPECTED = 10;public static void main (String[] args) {Context context = ZMQ.context(1);Socket publisher = context.socket(ZMQ.PUB);publisher.bind("tcp://*:5561");try {//zmq發送速度太快,在訂閱者尚未與發行者建立聯絡時,已經開始了資料發布Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace();}  int update_nbr;for (update_nbr = 0; update_nbr < 10; update_nbr++){publisher.send("Rhubarb".getBytes(), ZMQ.NOBLOCK);}publisher.send("END".getBytes(), 0);       publisher.close();context.term();}}

訂閱者:

package com.zeromq.test.Sync_pub_sub;import org.zeromq.ZMQ;import org.zeromq.ZMQ.Context;import org.zeromq.ZMQ.Socket;/** * @author 呂桂強 * @email larry.lv.word@gmail.com * @version 建立時間:2012-4-26 下午8:36:42 */public class syncsub {public static void main(String[] args) {Context context = ZMQ.context(1);Socket subscriber = context.socket(ZMQ.SUB);subscriber.connect("tcp://localhost:5561");subscriber.subscribe("".getBytes());int update_nbr = 0;while (true) {byte[] stringValue = subscriber.recv(0);String string = new String(stringValue);if (string.equals("END")) {break;}update_nbr++;System.out.println("Received " + update_nbr + " updates. :" + string);}subscriber.close();context.term();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.