Queue factory's RabbitMQ, queue's rabbitmq

Source: Internet
Author: User
Tags msmq

Queue factory's RabbitMQ, queue's rabbitmq

This article shares with you the usage of the RabbitMQ queue.Queue Factory (MSMQ)A simple factory has been set up during the description. Therefore, this chapter will not explain the factory code too much on the expanded sub-item; rabbitMQ should be one of the most widely used message queues in Internet companies. Look at this word in most recruitment scenarios. She has more diversified configurations than the MSMQ shared in the previous article, the number of Installation Steps is almost the same. The biggest difference is that MSMQ is a windows-bound service that can only be used on windows, while Rabbit currently supports many systems; when writing the second article of the queue factory, the Code has already been completed. Currently, the queue factory includes the following queues (Msmq, redis, rabbitmq), You can download the source code and test cases:QueueReposity-queue Factory; Hope everyone will like it, and hope you will have more"Support for code scanning"And"Recommendation"Thank you!

 

» RabbitMQ installation and console

» Encapsulate reading and writing of RabbitMQ queues

» Queue factory RabbitMQ Test Cases

 

Let's share it one step at a time:

» RabbitMQ installation and console

To install RabbitMQ, first download the RabbitMQ installation file for the corresponding server operating system, because she has installed versions for different operating systems; my local computer system is windows 7 (windows), so I went to the official website to download the installation package: Alibaba on rabbitmq.com. Click "windows" to download the package:


The latest version address:

Https://www.rabbitmq.com/releases/rabbitmq-server/v3.6.6/rabbitmq-server-3.6.6.exe;

Usually I enter the Installation Guides node on this interface-"With installer (recommended). At this time, I enter the help documentation required by the windows system. You can also select the version to download; the main purpose of entering this interface is to download an Erlang Windows Installation File (for more details, RabbitMq depends on the Erlang language). Click Erlang Windows Binary File to enter the download interface, then select the version corresponding to your operating system. If you are a Windows 64-bit user, you can download it at this address:

Http://erlang.org/download/otp_win64_19.2.exe

A friend who is new to RabbitMQ will ask why Erlang is needed, because it was developed by Erlang. Erlang is a common concurrency-oriented programming language, A Distributed language. After you install the erlang installation package, the Erlang Development Editor is available in the Start Menu of your computer, for the time being, this language word is generally used in the recruitment of first-class large companies, but not for small and medium companies. It may also be because few small and medium companies are involved in concurrency. The installation is complete here, the following Commands need to be executed through the command line. Because RabbitMQ has many configurations, I will certainly use a few examples here. For more details, refer to the official documentation:

First find the directory to install rabbitmq and enter the rabbitmq_server-3.6.6 to find the sbin folder-press and hold Shift + Right-click the sbin folder-in this place to open the command form-see this address enable rabbitmq_management-input in the cmd form just opened:


This is the instruction for enabling the rabbitmq manager. At this time, you can enter http: // localhost: 15672/in your browser to enter the monitoring background of rabbitmq through the visitor account:

Url: http: // localhost: 15672/

Username: guest

Password: guest

If you see the interface as shown in the figure, congratulations! You have successfully built the RabbitMQ service:


Because Rabbit not only has Queues, but also other routing and switch functions, we can see a lot of statistics or descriptions. Here we only use the Queues option, click to enter the Queues interface to see that there is no data, but there is a button to Add queue, this console allows you to manually Add a queue data, of course, this is not our topic today:


The above guest is enough for testing and use. You can refer to the following for the remaining Administrator Account or password settings:

Document for rabbitmqctl operations: https://www.rabbitmq.com/man/rabbitmqctl.1.man.html #

Plugins operation documentation: https://www.rabbitmq.com/plugins.html

 

» Encapsulate reading and writing of RabbitMQ queues

The official website of RabbitMQ is used in C # To list several methods. Here I choose to directly use the RabbitMQ provided by RabbitMQ. for the Client's nuget package, for the current nuget, version 4.0.0 and later must be NETFramework 4.5.1 or later or netcore, the Framework framework is used here, so the nuget package of this version is referenced:

Install-Package RabbitMQ. Client-Version 3.6.6

After the reference, you fill in the Code to the queue factory mentioned above. First, inherit the unified configuration file read class PublicClass. confClass <QRabbitMQ> and then implement the IQueue interface. Here we encapsulate several common operation methods of RabbitMq. The specific code is as follows:

1 /// <summary>
 2 /// RabbitMq
 3 /// </ summary>
 4 public class QRabbitMQ: PublicClass.ConfClass <QRabbitMQ>, IQueue
 5 {
 6 private IConnection con = null;
 7
 8 public void Create ()
 9         {
10 if (string.IsNullOrWhiteSpace (this.ApiUrl) || string.IsNullOrWhiteSpace (this.ApiKey)) {throw new Exception ("Creating a RabbitMq queue requires a specified queue: HostName and Port");}
11
12 try
13 {
14 var factory = new ConnectionFactory () {HostName = this.ApiUrl, Port = Convert.ToInt32 (this.ApiKey)};
15 con = con ?? factory.CreateConnection ();
16}
17 catch (Exception ex)
18 {
19 throw new Exception (ex.Message);
20}
twenty one         }
twenty two 
23 public long Total (string name = "Redis_01")
twenty four         {
25 if (con == null) {throw new Exception ("Please create a queue connection first");}
26 using (var channel = con.CreateModel ())
27 {
28 return channel.MessageCount (name);
29}
30}
31
32 public Message Read (string name = "RabbitMQ_01")
33 {
34 if (con == null) {throw new Exception ("Please create a queue connection first");}
35 if (string.IsNullOrWhiteSpace (name)) {throw new Exception ("name cannot be empty");}
36
37 var message = new Message ();
38 message.Label = name;
39 message.Formatter = new XmlMessageFormatter (new Type [] {typeof (string)});
40 using (var channel = con.CreateModel ())
41 {
42 var baseResult = channel.BasicGet (name, true); // true: delete queue after acquisition false: do not delete
43 if (baseResult == null) {return message;}
44 var body = baseResult.Body;
45 message.Body = Encoding.UTF8.GetString (body);
46}
47 return message;
48}
49
50 public bool Write (string content, string name = "RabbitMQ_Queue01")
51 {
52 if (con == null) {throw new Exception ("Please create a queue connection first");}
53 if (string.IsNullOrWhiteSpace (content) || string.IsNullOrWhiteSpace (name)) {throw new Exception ("Content and name cannot be empty");}
54
55 using (var channel = con.CreateModel ())
56 {
57 channel.QueueDeclare (name, false, false, false, null);
58 var body = Encoding.UTF8.GetBytes (content);
59
60 channel.BasicPublish (string.Empty, name, null, body);
61 return true;
62}
63}
64
65 public void Dispose ()
66 {
67 if (con! = Null)
68 {
69 con.Close ();
70 con.Dispose ();
71 con = null;
72}
73}
74}

The main process of the Code is: Create (Create)-Read (Read) | Write (Write)-release (Dispose); with the specific RabbitMq implementation class, in the factory, you can directly obtain the object of the implementation class through generic ing:

1 /// <summary>
  2 /// ====================
  3 /// author: God Bull Walking 3
  4 /// des: This column is open source, including queues with MSMQ, RedisMQ, RabbitMQ
  5 /// blogs: http://www.cnblogs.com/wangrudong003/
  6 /// ====================
  7 /// queue factory
  8 /// </ summary>
  9 public class QueueReposity <T> where T: class, IQueue, new ()
10 {
11 public static IQueue Current
12 {
13 get
14 {
15 return PublicClass.ConfClass <T> .Current;
16}
17}
18}

 

» Queue factory RabbitMQ Test Cases

By configuring the environment and encapsulating your own method above, a simple test case is written here, which can be divided into Server (add to Message Queue) and Client (get Message Queue). First, let's look at the Server code:

1 /// <summary>
 2 /// Queue server test case
 3 /// </ summary>
 4 class Program
 5 {
 6 static void Main (string [] args)
 7 {
 8 // Redis_Server ();
 9 
10 RabbitMQ_Server ();
11
12 // MSMQ_Server ();
13}
14 private static void RabbitMQ_Server ()
15 {
16 // Instantiate the QMsmq object
17 var mq = QueueReposity <QRabbitMQ> .Current;
18
19 try
20 {
21 Console.WriteLine ("Server-side creation: RabbitMQ instance");
22 mq.Create ();
twenty three 
24 var num = 0;
25 do
26 {
27 Console.WriteLine ("Enter the number of loops (number, 0 means end):");
28 var readStr = Console.ReadLine ();
29 num = string.IsNullOrWhiteSpace (readStr)? 0: Convert.ToInt32 (readStr);
30
31 Console.WriteLine ("Insert data:");
32 for (int i = 0; i <num; i ++)
33 {
34 var str = "My number is:" + i;
35 mq.Write (str);
36 Console.WriteLine (str);
37}
38} while (num> 0);
39}
40 catch (Exception ex)
41 {
42}
43 finally
44 {
45 Console.WriteLine ("Release.");
46 mq.Dispose ();
47}
48 Console.ReadLine ();
49}
50}

Using the Create-Read-Write-Dispose process to use our queue factory is quite simple, at this point, run the Server and enter the parameters:


At this time, 11 pieces of data are added to the RabbitMq queue. We use her background to find the added queue:


We can see the total number and name of the queue we just inserted. If you want to see the specific content, you can click the name "mq_01" to enter the interface of a queue, find the "Get messages" option in the scroll bar below. By default, we can see that Messages is 1 and change it to 10. Then click get messages to see the specific content we just inserted:


It's a little long. I don't know if dudu will blame me. Haha, here we can see that queue insertion is successful, and then we will consume the queue through the client. The Code is as follows:

1 /// <summary>
 2 /// queue client test case
 3 /// </ summary>
 4 class Program
 5 {
 6 static void Main (string [] args)
 7 {
 8 // RedisMQ_Client ();
 9 
10 RabbitMQ_Client ();
11
12 // MSMQ_Client ();
13}
14
15 private static void RabbitMQ_Client ()
16 {
17 // Instantiate the QMsmq object
18 var mq = QueueReposity <QRabbitMQ> .Current;
19 try
20 {
21 Console.WriteLine ("Client-side creation: RabbitMQ instance");
22 mq.Create ();
twenty three 
24 while (true)
25 {
26 try
27 {
28 var total = mq.Total ();
29 if (total> 0) {Console.WriteLine ("Number of queues:" + total);}
30
31 var result = mq.Read ();
32 if (result.Body == null) {continue;}
33 Console.WriteLine (string.Format ("Accept queue {0}: {1}", result.Label, result.Body));
34}
35 catch (Exception ex)
36 {Console.WriteLine ("Exception message:" + ex.Message);}
37}
38}
39 catch (Exception ex)
40 {
41 throw ex;
42}
43 finally
44 {
45 Console.WriteLine ("Release.");
46 mq.Dispose ();
47}
48}
49} 

Let's run the exe to see the effect:


At this moment, the data that has just been added to the queue has been read and taken out. Now let's look at the Rabbitmq console. get messages cannot get specific content because the client consumes data, the data in the queue is automatically cleared. If you want to clear the data, the setting is in the Code:

1 var baseResult = channel. BasicGet (name, true);
 // true: delete a queue after obtaining it; false: Do not delete

The code sharing and environment setup for the encapsulated RabbitMQ are described above. I hope this will help you better. Thank you for reading;


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.