zoukankan      html  css  js  c++  java
  • 转发在.NET上使用ZeroMQ

    原文来自于:http://www.imneio.com/2009/10/zeromq_in_dotnet/

    ZeroMQ的.NET封装很简单,基本上是来自C-API的,但有所简化。使用上,由于习惯了在C#里面用强类型约束,API上的int类型让我感觉封装得”非常不.NET”

    首先要明确下ZeroMQ的几个概念:

    1. Exchange & Queue:Exchange 是系统数据交换的基础,Queue是消息通道,当Exchange与Queue绑定后,向Exchange提交消息,就会流到其绑定的Queue(s)中。

    2. 接收端创建一个Queue后,就能从里面获取内容。

    3.Zmq_server: 这个是ZeroMQ消息的核心程序,负责调度消息,是ZeroMQ系统的”CPU”。

    由于是轻量级的,在.NET下使用ZeroMQ也非常简单:

    1. libclrzmq.dll 是封装过的.NET客户端,引用之。运行的时候记得把zeromq的bin下的其他dll也复制过去。

    2. 运行zmq_server.exe服务:

    1
    zmq_server --port 5555

    其中,5555是服务的端口。也可以用–config来指定配置文件,这里不详述。

    3. 消息发送与接收:

    发送端:

    1
    2
    3
    4
    5
    Zmq q = new Zmq();
    q.Open("127.0.0.1:5555");
    int ex = q.CreateExchange("EX1", null,  Zmq.SCOPE_LOCAL, Zmq.STYLE_LOAD_BALANCING);
    Zmq.Bind("EX1","Q1", null, null);
    Zmq.Send(ex, new byte[]{1,2,3,5}, false);

    接收端:

    1
    2
    3
    4
    5
    6
    Zmq q = new Zmq();
    q.Open("127.0.0.1:5555");
    int ex = q.CreateQueue("Q1",  Zmq.SCOPE_GLOBAL, "127.0.0.1:5556",Zmq.NO_LIMIT,Zmq.NO_LIMIT, Zmq.NO_SWAP);
    int outType;
    byte[] data;
    Zmq.Receive( out data, out outType, true);//阻塞方式接收

    上面代码中,STYLE_LOAD_BALANCING表示数据被一个接收端接收到后就结束,若改为STYLE_DATA_DISTRIBUTION则表示数据将会发送到每个接收端上。
    此外,根据官方的文档:
    SCOPE_LOCAL
    Local scope means that the object (exchange or queue) is visible only within the engine that created it.
    SCOPE_PROCESS:
    Process scope means that the object is visible to all the engines within the process registered with the same dispatcher object.
    SCOPE_GLOBAL:
    Global scope means that the object is visible to all the 0MQ processes registered with the same zmq_server.

    注意事项,上述程序的接收端需要先启动,然后再启动发送端,否则发送端在BindQ1的时候将找不到队列而出错。

  • 相关阅读:
    centos6 vps部署rails
    初始设置ubuntu 16.04 Vps部署rails
    自己买的书籍
    linux mint 18.2 install erlang
    Bunder: What does :require => nil in Gemfile mean?
    javascript箭头函数
    SharpGL学习笔记(一) 平台构建与Opengl的hello World
    动力学仿真引擎ODE的学习笔记,C#演示(一)
    设计模式之 面向对象的养猪厂的故事,C#演示(二)
    设计模式之 面向对象的养猪厂的故事,C#演示(一)
  • 原文地址:https://www.cnblogs.com/amityat/p/2160306.html
Copyright © 2011-2022 走看看