Easy-to-use. NET free open-source RabbitMQ operation component EasyNetQ resolution, rabbitmqeasynetq

Source: Internet
Author: User
Tags msmq rabbitmq

Easy-to-use. NET free open-source RabbitMQ operation component EasyNetQ resolution, rabbitmqeasynetq

For most of the current. NET projects, the technology stacks are almost the same. It is estimated that the development projects are seldom used for controls. After all, there are a lot of problems. Pair. NET project. Currently, the architecture ASP. net mvc, ASP. NET WebAPI, ORM (more Dapper. (. NET built-in Memcache, or Redis), requests for many projects, use Nginx for load balancing and queue, and so on.

The above briefly introduces the technical architecture of the. NET project. The specific technology can be selected based on the specific needs. Many people will be familiar with the queue, such as MSMQ and RabbitMQ. Since you need to use a queue, you need to consider how to use a better C # operation queue.

1. RabbitMQ Overview

In current projects, message queues are frequently used and there are many types of message queues, such as ActiveMQ, RabbitMQ, ZeroMQ, Kafka, MetaMQ, and RocketMQ. Message queue middleware is an important component in a distributed system. It mainly solves problems such as application coupling, asynchronous messages, and traffic charge splitting. High performance, high availability, scalability, and eventual consistency architecture. Is an indispensable middleware for large-scale distributed systems.

This section describes RabbitMQ message queues and supports the open Advanced Message Queue Protocol (AMQP ). Features of RabbitMQ: powerful application message delivery; easy to use; running on all major operating systems; support for a large number of developers platforms; open-source and commercial support. The message Queue mode can be P2P (Point to Point). The P2P mode has three roles: Queue, Sender, and Receiver ). Each message is sent to a specific queue, and the receiver obtains the message from the queue. The queue retains messages until they are consumed or time-out. Publish/Subscribe (Pub/Sub), including three Topic, Publisher, and Subscriber ). Multiple publishers send messages to topics. The system sends these messages to multiple subscribers.

The above describes the relevant features and modes of RabbitMQ. If you have more knowledge, you will not need to know about the installation and configuration. You can go to the official website for a detailed understanding.

Ii. EasyNetQ component Overview

The application scenarios and usage modes of RabbitMQ are described above. in the development of the NET project, MSMQ is often used as a message queue. Many people are familiar with MSMQ operations and are also lightweight message queues. RabbitMQ is a heavyweight Message Queue with multiple language versions. As a. NET developer, RabbitMQ may have fewer operations. In the. NET project, we will introduce EasyNetQ, A. NET component used to operate RabbitMQ.

EasyNetQ aims to provide a library that makes RabbitMQ in. NET as simple as possible. In EasyNetQ, messages are represented by the. NET type, and messages are routed by the. NET type. EasyNetQ routes messages. When a message is published, EasyNetQ checks its type and provides a route key based on the Type name, namespace, and assembly body. In terms of consumption, the user subscription type. After the subscription type, messages of this type are routed to the subscribers. By default, EasyNetQ uses the Newtonsoft. Json library to serialize the. NET type to JSON. Therefore, you can use RabbitMQ to manage applications and other tools to debug message problems.

EasyNetQ is a set of components that provide services on the RabbitMQ. Client library. These operations can be like serialization, error processing, thread grouping, connection management, etc. They are composed of mini-IoC containers. You can easily replace any component with your own implementations. Therefore, if you want XML serialization instead of built-in JSON, you only need to write an ISerializer implementation and register it to the container.

The following is an official structure chart, which can be used to parse the structure of the component:

Var bus = rabbithuch. CreateBus ("host = myServer; virtualHost = myVirtualHost; username = mike; password = topsecret ");

The delayed connection with the RabbitMQ server is represented by the IBus interface. The connection string created by the connection is composed of key/value pairs in the format of key = value, each of which is separated by a semicolon. Host: host address; virtualHost: Default virtual host '/'; username: User Name; default value: 'guest '; password: password; default value: 'guest ';

2. Close the connection:

bus.Dispose();

To close the connection, simply process the bus, which will close the connection, channel, consumer, and all other resources used by EasyNetQ.

 3. Publish a message:

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

4. subscribe to Emails:

bus.Subscribe<MyMessage>("my_subscription_id", msg => Console.WriteLine(msg.Text));

5. Remote process 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 provides excellent features. Topic-based routing allows subscribers to filter messages based on multiple criteria. * (Asterisk) matches a word. # (Hash) matches zero or multiple words.

Iv. Analysis of core objects of EasyNetQ Components

The above briefly introduces the application method of this component. There are still many methods not introduced, and you can have a deep understanding of what you need. Here we will introduce some core objects of this component.

 1. rabbithuch. CreateBus ():

 public static IBus CreateBus(ConnectionConfiguration connectionConfiguration, AdvancedBusEventHandlers advancedBusEventHandlers, 
             Action<IServiceRegister> registerServices)
        {
            Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration");
            Preconditions.CheckNotNull(advancedBusEventHandlers, "advancedBusEventHandlers");
            Preconditions.CheckNotNull(registerServices, "registerServices");
            var container = createContainerInternal();
            if (container == null)
            {
                throw new EasyNetQException("Could not create container. " +
                    "Have 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 CreateBus () method is mainly contained in the rabbithuch class and has 12 reloads. This method connects to the server based on the user's connection configuration information. This method receives three parameters. connectionConfiguration indicates connecting to the instance. advancedBusEventHandlers is used to add the AdvancedBusEventHandlers instance of the processing program to the newly created IBus. Advanced event. RegisterServices overwrites the default service. ComponentRegistration. RegisterServices (container); register the default EasyNetQ component in our ultra-simple IoC container. Container. Resolve <IBus> () gets the instance of the requested service. Note that all services are single-instance, and multiple calls to 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 messages. This method is a virtual method that can be rewritten in sub-classes. Var configuration = new PublishConfiguration (conventions. TopicNamingConvention (typeof (T) is used to define the configuration of publish information, and Message is used to define the mail body content.

V. Summary

The above is a brief introduction to this component. If you need to learn more, you can study and study it on your own. Knowledge lies in your diligence. Others are just a simple guide.


Related Article

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.