NETMQ Publish Subscription C # sample

Source: Internet
Author: User

NETMQ (ZeroMQ to. Net), ØMQ claims to be the fastest middleware in history. It encapsulates the socket communication so that we do not need to write the socket function call to complete complex network communication. Unlike Message Queuing products in general, it does not have a Message Queuing server and is more like a network communication library. From the point of view of network communication, it is above the session layer and under the application layer. "ZeroMQ official website":http://zeromq.org

ØMQ has 4 basic communication models: one pair model (Exclusive-pair), a request response model (request-reply), a publish subscription model (Publish-subscribe), a push-pull model (push-pull), respectively.

request-reply Pattern Request-Reply model

    • This model is primarily used to send requests from the client to one or more service instances, and then waits for a reply to each request immediately thereafter
    • The inside is also specific zmq_req zmq_rep Zmq_dealer zmq_router
    • REQ after sending a message, you must receive a response message before you can send a new message
    • Rep returns a message when it receives a message

Publish-subscribe Pattern Publish-Subscribe mode

    • This mode is primarily used for 1-to-many data releases (one publisher, multiple subscribers)
    • There's a specific zmq_pub zmq_sub.
    • Pub sends a message to all sub. If the sub does not start at this point, the message will be missed the next time it starts

Pipeline Pattern Piping Mode

    • This pattern is primarily used to publish data to nodes arranged by pipelines, and data is always flowing along the pipeline. At least one node is connected in each pipeline stage
    • There's a specific Zmq_push zmq_pull.
    • An implementation of a 1-to-n queue, push puts data into a queue, and pull does not fetch data from the queue. The data is sent to each pull in a load-balanced

Exclusive pair pattern Independent pair mode

    • Peer to peer mode. Primarily for intra-process inter-thread communication
    • It's got a specific zmq_pair.
    • The implementation of the 1-to-1 queue between threads is implemented with lock free, so it is fast

The following is sample code for a subscription publication:

To publish the service side:

  public static class Netmqpub {readonly static ManualResetEvent _terminateevent = new ManualResetEvent (false);            <summary>//NETMQ Release mode///</summary> public static void Start () {            string[] wethers = new String[5] {"Sunny", "cloudy", "cloudy", "drizzle", "Blizzard"};            CTRL + C Exit Program console.cancelkeypress + = console_cancelkeypress;            Console.WriteLine ("Publish Multiple regional Weather forecasts:"); using (var context = Netmqcontext.create ()) {using (var publisher = context. Createpublishersocket ()) {Publisher.                    Bind ("tcp://127.0.0.1:5556");                    var rng = new Random ();                    String msg;                    int sleeptime = 10;                        while (_terminateevent.waitone (0) = = False) {//randomly generate weather data int zipcode = rng.                        Next (0, 99); int temperature = rng. Next (-50, 50); int wetherid = rng.                        Next (0, 4); msg = string.                        Format ("{0} {1} {2}", ZipCode, temperature, Wethers[wetherid]); Publisher. Send (Msg,encoding.utf8, ZMQ.                        sendreceiveoptions.dontwait);                        Console.WriteLine (msg);                    Thread.Sleep (Sleeptime); }}}} static void Console_cancelkeypress (object sender, Consolecanceleventargs E            {Console.WriteLine ("Exit ...");        _terminateevent.set (); }    }

Subscribing to clients, you can launch multiple instances to simulate receiving weather information:

  public static class Netmqsub {public delegate void Getdatahandler (String message);        public static event Getdatahandler Ongetdata;                        <summary>//NETMQ Subscription mode///</summary> public static void Start () {            var rng = new Random (); int zipcode = rng.            Next (0, 99);            Console.WriteLine ("Receive local weather forecast {0} ...", zipcode);                Ongetdata + = new Getdatahandler (processdata); using (var context = netmqcontext.create ()) using (var subscriber = context. Createsubscribersocket ()) {Subscriber.                Connect ("tcp://127.0.0.1:5556"); Subscriber. Subscribe (ZipCode.                ToString (CultureInfo.InvariantCulture)); while (true) {string results = Subscriber.                    Receivestring (Encoding.UTF8);                    Console.Write ("."); string[] Split = results. Split (new[] {"}, StringsplitoptionS.removeemptyentries); int zip = Int.                    Parse (Split[0]);                    if (zip = = zipcode) {ongetdata (results);            }}}} public static void ProcessData (String msg) {        Console.WriteLine ("Weather conditions:" + msg); }    }

  

NETMQ Publish Subscription C # sample

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.