Easy to use. NET free open source RABBITMQ operation component EASYNETQ parsing

Source: Internet
Author: User
Tags msmq rabbitmq

For the present most. NET project, in fact, the use of the technology stack is almost, estimates are now rarely used in control development projects, after all, a lot of problems. For. NET projects, currently more appropriate for the architecture of ASP. Mvc,asp.net WebAPI, ORM (more dapper.net or its extensions, slightly larger projects with EF, etc.), in order to increase the speed will also adopt the cache (. NET comes with Memcache, or Redis), request more projects, use Nginx to do load balancing and use queues and so on.

A brief introduction to the above. NET project, the specific technology based on the specific needs to make choices. Introduced to the queue, many people will be familiar with, such as MSMQ,RABBITMQ and so on queue. Now that you need to use a queue, consider how to use C # to better manipulate the queue.

I. RABBITMQ overview

In the current project, the use of Message Queuing is more frequent, the type of Message Queuing is also more, such as: ACTIVEMQ,RABBITMQ,ZEROMQ,KAFKA,METAMQ,ROCKETMQ. Message Queue Middleware is an important component in distributed system, which mainly solves the problems of application coupling, asynchronous message and traffic cutting front. Achieve high performance, high availability, scalability and eventual consistency architecture. is an indispensable middleware for large-scale distributed systems.

Here is the main introduction to RABBITMQ Message Queuing, which supports an open advanced Message Queuing Protocol (AMQP). RABBITMQ Features: powerful application messaging, easy to use, running on all major operating systems, support for a large number of developer platforms, Open source and business support. There are two modes of the Message Queuing pattern: Peer (Point-to-point), which has three roles: Message Queuing (queue), Sender (sender), receiver (receiver). Each message is sent to a specific queue, and the recipient obtains the message from the queue. The queue retains messages until they are consumed or timed out. Publish/subscribe (Pub/sub), contains three role topics (Topic), publisher (publisher), Subscriber (subscriber). Multiple publishers send messages to topic, which the system passes to multiple subscribers.

The above describes the relevant characteristics and patterns of rabbitmq, more knowledge is no longer introduced, need to understand the installation and configuration, you can enter the official website for detailed understanding.

Two. EASYNETQ Components overview

The application scenarios and patterns of RABBITMQ are described above, and in. NET project development, more use of MSMQ as Message Queuing, many people are familiar with the operation of MSMQ, also belong to the lightweight message queue. For RABBITMQ is a more heavyweight message queue, there are multiple language versions, as. NET developers may be less likely to operate on RABBITMQ. How to use RABBITMQ more conveniently in. NET projects is described here. NET Operation RABBITMQ component Easynetq.

The goal of EASYNETQ is to provide a library that makes RABBITMQ as simple as possible in. Net. The message should be represented by a. NET type in Easynetq, and the message should be routed through its. NET type. EASYNETQ is routed by message type. When a message is published, EASYNETQ checks its type and gives a routing key based on the type name, namespace, and assembly. On the consumer side, the user subscription type. After the subscription type, messages of that type are routed to subscribers. By default, EASYNETQ uses the Newtonsoft.json library to serialize. NET types into JSON. This has the advantage that the message is human readable, so you can use tools such as the RABBITMQ management application to debug message problems.

EASYNETQ is a collection of components that provide services on top of the Rabbitmq.client library. These operations can be like serialization, error handling, thread teaming, connection management, and so on. They are made up of MINI-IOC containers. You can easily replace any component with your own implementation. So, if you want XML serialization instead of built-in JSON, just write a Iserializer implementation and register it with the container.

The following is an official structure diagram that can be used to parse the structure of the component:

Three. How to use EASYNETQ components

Introduce the background of the EASYNETQ component, and now you need to describe how the component is used. EASYNETQ components are simple to use, similar to many components, such as establishing a connection, doing something, and so on, for EASYNETQ components.

1. Create the connection:

var bus = Rabbithutch.createbus ("Host=myserver;virtualhost=myvirtualhost;username=mike;password=topsecret");

A deferred connection to the RABBITMQ server is represented by the IBUs interface, where the connection string is made up of key/value pairs in the form key = value, each separated by a semicolon (;). Host: VirtualHost: Default is the default virtual host '/'; Username: username, default is ' guest '; password: password, default is ' guest ';

2. Close the connection:

Bus. Dispose ();

To close the connection, simply handle the bus, which will shut down the connections, channels, consumers, and all other resources used by EASYNETQ.

3. Post a message:

var message = new Mymessage {Text = "Hello Rabbit"};bus. Publish (message);

4. Subscribe to Email:

Bus. Subscribe<mymessage> ("my_subscription_id", msg = Console.WriteLine (msg). Text));

5. Remote Procedure Call:

var request = new Testrequestmessage {Text = "Hello from the Client!"}; Bus. Request<testrequestmessage, testresponsemessage> (request, Response =     Console.WriteLine ("Got response : ' {0} ', Response. Text));

6.RPC Server:

Bus. Respond<testrequestmessage, testresponsemessage> (request =     new testresponsemessage{Text = Request. Text + "All done!"});

7. Recorder:

var logger = new MyLogger (), var bus = Rabbithutch.createbus ("My connection string", x = = X.register<ieasynetqlogger > (_ = Logger));

8. Routing:

Bus. Subscribe ("my_id", handler, x = X.withtopic ("x.*"));

RABBITMQ has a very good feature, topic-based routing that allows subscribers to filter messages based on multiple criteria. * (asterisk) matches one word. # (hash) matches 0 or more words.

Four. EASYNETQ component Core Object parsing

The above simple introduction of the application of the component, there are more ways not to do the introduction, but also need to do in-depth understanding. Here is a look at some of the core objects of the component.

1.rabbithutch.createbus ():

public static IBus Createbus (Connectionconfiguration connectionconfiguration, advancedbuseventhandlers Advancedbuseventhandlers,
Action<iserviceregister> registerservices) {preconditions.checknotnull (Connectioncon figuration, "connectionconfiguration"); Preconditions.checknotnull (Advancedbuseventhandlers, "advancedbuseventhandlers"); Preconditions.checknotnull (registerservices, "registerservices"); var container = createcontainerinternal (); if (container = = null) {throw new Easynetqexception ("Could not create container." + "You called Setcontainerfactory (...) With a function that returns null? ");} Connectionconfiguration.validate (); Container. Register (_ = = Connectionconfiguration); Container. Register (_ = = Advancedbuseventhandlers); Registerservices (container); Componentregistration.registerservices (container); Return container. Resolve<ibus> (); }

The main method contained in the Rabbithutch class is the Createbus () method, which has 12 overloads. This method is mainly based on the user's connection configuration information and connects to the service side. The method receives three parameters, Connectionconfiguration represents a connection instance, Advancedbuseventhandlers the event that is used to add the Advancedbuseventhandlers instance of the handler to the newly created ibus.advanced. Registerservices overrides the default service. Componentregistration.registerservices (container); registers the default EASYNETQ component in our internal ultra-simple IOC container. Container. Resolve<ibus> () Gets the instance of the requested service. Note that all services are singleton, and multiple calls resolve will return the same instance.

2.ibus.publish ():

  public virtual void publish<t> (T message, action<ipublishconfiguration> Configure) where T:class {            Preconditions.checknotnull (Message, "message");            Preconditions.checknotnull (Configure, "Configure"); var configuration = new Publishconfiguration (conventions.            Topicnamingconvention (typeof (T)));            Configure (configuration);            var messageType = typeof (T);                    var easynetqmessage = new Message<t> (Message) {Properties = {            DeliveryMode = Messagedeliverymodestrategy.getdeliverymode (MessageType)}}; if (configuration. Priority! = NULL) easyNetQMessage.Properties.Priority = Configuration.            Priority.value; if (configuration. Expires = null) easyNetQMessage.Properties.Expiration = Configuration.            Expires.tostring (); var exchange = Publishexchangedeclarestrategy.declareexchAnge (Advancedbus, MessageType, exchangetype.topic); Advancedbus.publish (Exchange, configuration.        Topic, False, easynetqmessage); }

This method is used to publish a message, which is a virtual method that can be overridden in subclasses. var configuration = new Publishconfiguration (conventions. Topicnamingconvention (typeof (T))) is used to define the configuration of the publication information, and message defines the message body content.

Five. Summary

The above is a simple introduction to the component, if you need to learn more about the content can be in-depth study and research. Knowledge lies in one's own diligence, others are just a simple guide.

Http://www.cnblogs.com/pengze0902/p/6654296.html

Easy to use. NET free open source RABBITMQ operation component EASYNETQ parsing

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.