• 转发在.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的时候将找不到队列而出错。

  • 相关阅读:
    UUID含义及ubuntu配置系统默认JDK
    MYSQL 问题小总结
    纯CSS3实现常见多种相册效果
    Docker Api 实测
    Dijkstra with priority queue 分类: ACM TYPE 2015-07-23 20:12 4人阅读 评论(0) 收藏
    hash值的计算与转换 分类: ACM TYPE 2015-05-07 17:49 36人阅读 评论(0) 收藏
    NYOJ
    进制转换函数 2015-02-15 09:41 32人阅读 评论(0) 收藏
    操作系统图解 2015-02-03 23:44 71人阅读 评论(0) 收藏
    [kuangbin带你飞]专题一 简单搜索
  • 原文地址:https://www.cnblogs.com/amityat/p/2160306.html
Copyright © 2020-2023  润新知