Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

RabbitMQ of the queue factory

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

What I share with you this time is the use of RabbitMQ queues. In the previous article, queue factory (MSMQ) has already built a simple factory when it is described, so the sub-items expanded on it will no longer explain the factory code too much. RabbitMQ should be one of the most frequently used message queues for Internet companies. Look at the appearance of this word in recruitment. Compared with the MSMQ shared in the previous article, the configuration of MSMQ is more diversified, and the number of installation steps is about the same. The biggest difference is that windows bundled services can only be used on windows, while Rabbit currently supports more systems. When writing the second article on queue factory, in fact, the code has already been completed. At present, the queue factory includes the following queues (msmq,redis,rabbitmq). You can download the source code and test cases: QueueReposity- queue factory. I hope you like it and hope that you have a lot of "scan code support" and "recommendation" Thank you!

RabbitMQ installation and console

Encapsulate the read and write of RabbitMQ queues

RabbitMQ test case for queue factory

Let's share it one step at a time:

RabbitMQ installation and console

To install RabbitMQ, we first need to download the RabbitMQ installation file of the corresponding server operating system, because she has different installation versions of the operating system, which needs to be noted. My local computer system is win7 (belongs to windows), so go to the official website to download the installation package: https://www.rabbitmq.com/. After entering the official website, select "Installation". You can see many download sources of the installation version. Here, you can choose to download from Downloads on rabbitmq.com, and click "windows" to download:

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 of this interface-"With installer (recommended). At this time, I enter the help documents needed by the windows system. You can also choose the version to download." The main purpose of entering this interface is to download an installation file of Erlang Windows (deeper reason: the operation of RabbitMq depends on Erlang language). Click Erlang Windows Binary File to enter the download interface, and then select the corresponding version of your operating system. If you are also a windows64 bit, you can download it directly with this address:

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

Now that the two necessary things have been downloaded, first install exe in the Erlang language, and then install rabbitmq-server-3.6.6.exe;. Friends who have just come into contact with RabbitMQ will ask why they need the support of Erlang, because she was developed by Erlang. Erlang is a general concurrency-oriented programming language dedicated to writing a distributed language. When you install the erlang installation package mentioned above, there is an Erlang development editor in the start menu of your computer, which you can use to practice sometime. At present, this language word generally appears in the recruitment of first-class large companies, but generally does not exist in small and medium-sized companies, probably because very few small and medium-sized companies will involve concurrency. The installation is completed here. The following instructions need to be executed through the command line. Since there are a lot of RabbitMQ configurations, I will definitely use a few of them here to demonstrate. For other details, please refer to the official documentation:

First, find the directory where rabbitmq is installed and go to rabbitmq_server-3.6.6 to find the sbin folder-"hold down the Shift+ right mouse button sbin folder -" Open the command form here-"refer to the https://www.rabbitmq.com/management.html command: rabbitmq-plugins enable rabbitmq_management -" enter into the cmd form you just opened:

This is the command to open the rabbitmq manager. At this time, you can enter http://localhost:15672/ in your browser and enter the rabbitmq monitoring backend through the visitor account:

Url: http://localhost:15672/

Username:guest

Password:guest

If you see the following interface at the moment, congratulations on your success in building the RabbitMQ service:

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

The above guest is enough for us to test. As for the remaining administrator account or password settings, you can see this:

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

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

Encapsulate the read and write of RabbitMQ queues

Several methods are listed on the official website of RabbitMQ in C#. Here I choose to use the nuget package of RabbitMQ.Client directly. For the current nuget, version 4.0.0 and above must be NETFramework version 4.5.1 or above or netcore version. The author uses the Framework4.5 framework here, so I quote this version of the nuget package:

Install-Package RabbitMQ.Client-Version 3.6.6

After the reference, fill in the code for the queue factory mentioned earlier, first inherit the unified configuration file read class PublicClass.ConfClass, and then implement the IQueue interface. Here, several common operation methods of RabbitMq are encapsulated, and the specific code:

/ RabbitMq / / public class QRabbitMQ: PublicClass.ConfClass, IQueue {private IConnection con = null; public void Create () {if (string.IsNullOrWhiteSpace (this.ApiUrl) | | string.IsNullOrWhiteSpace (this.ApiKey)) {throw new Exception ("queues: HostName and Port are required to create RabbitMq queues") } try {var factory = new ConnectionFactory () {HostName = this.ApiUrl, Port = Convert.ToInt32 (this.ApiKey)}; con = con? Factory.CreateConnection ();} catch (Exception ex) {throw new Exception (ex.Message);}} public long Total (string name = "Redis_01") {if (con = = null) {throw new Exception ("Please create queue connection first") } using (var channel = con.CreateModel ()) {return channel.MessageCount (name);}} public Message Read (string name = "RabbitMQ_01") {if (con = = null) {throw new Exception ("Please create queue connection first") } if (string.IsNullOrWhiteSpace (name)) {throw new Exception ("name cannot be empty");} var message = new Message (); message.Label = name; message.Formatter = new XmlMessageFormatter (new Type [] {typeof (string)}); using (var channel = con.CreateModel ()) {var baseResult = channel.BasicGet (name, true) / / true: delete queue false after acquisition: do not delete if (baseResult = = null) {return message;} var body = baseResult.Body; message.Body = Encoding.UTF8.GetString (body);} return message } public bool Write (string content, string name = "RabbitMQ_Queue01") {if (con = = null) {throw new Exception ("Please create a queue connection first");} if (string.IsNullOrWhiteSpace (content) | | string.IsNullOrWhiteSpace (name)) {throw new Exception ("content and name cannot be empty") } using (var channel = con.CreateModel ()) {channel.QueueDeclare (name, false, null); var body = Encoding.UTF8.GetBytes (content); channel.BasicPublish (string.Empty, name, null, body); return true }} public void Dispose () {if (con! = null) {con.Close (); con.Dispose (); con = null;}

The code mainly uses the following process: create (Create)-"Read | Write (Write) -" release (Dispose); with a specific RabbitMq implementation class, get the object of the implementation class directly through generic mapping in the factory:

/ author: Shenniu Walk 3 / des: the factory is open source, including MSMQ,RedisMQ in the queue. RabbitMQ / blogs: http://www.cnblogs.com/wangrudong003/ queue factory / public class QueueReposity where T: class,IQueue, new () {public static IQueue Current {get {return PublicClass.ConfClass.Current }}}

RabbitMQ test case for queue factory

Through the above method of configuring the environment and encapsulating yourself, a simple test case is written here, which is divided into Server (join message queue) and Client (get message queue). First, let's look at the code on the server side:

/ queue server test case / class Program {static void Main (string [] args) {/ / Redis_Server (); RabbitMQ_Server (); / / MSMQ_Server () } private static void RabbitMQ_Server () {/ / instantiate QMsmq object var mq = QueueReposity.Current; try {Console.WriteLine ("server creation: RabbitMQ instance"); mq.Create (); var num = 0 Do {Console.WriteLine ("enter the number of loops (number, 0 means end):"); var readStr = Console.ReadLine (); num = string.IsNullOrWhiteSpace (readStr)? 0: Convert.ToInt32 (readStr); Console.WriteLine ("insert data:") For (int I = 0; I

< num; i++) { var str = "我的编号是:" + i; mq.Write(str); Console.WriteLine(str); } } while (num >

0);} catch (Exception ex) {} finally {Console.WriteLine ("release.") ; mq.Dispose ();} Console.ReadLine ();}}

It is easy to use our queue factory through the process of creating (Create)-"Read (Read) | Write (write) -" release (Dispose). At this time, we run the Server side and enter the parameters:

At this time, 11 pieces of data were added to the RabbitMq queue, and we went to find the queue just added through her backend:

You can see the total number and name of the queues we have just inserted. If you want to see the specific contents, click the name "mq_01" to enter the interface of a queue, and then pull down the scroll bar to find the "Get messages" option. By default, the Messages is 1. We modify it to 10, and then click get messages to see the specific content we just inserted in the following figure:

The screenshot is a bit long. I wonder if dudu will blame me. Haha, you can see that the queue insertion is successful here, and then we will consume the queue through the client. The specific code:

/ queue client test case / class Program {static void Main (string [] args) {/ / RedisMQ_Client (); RabbitMQ_Client (); / / MSMQ_Client () } private static void RabbitMQ_Client () {/ / instantiate QMsmq object var mq = QueueReposity.Current; try {Console.WriteLine ("client creation: RabbitMQ instance"); mq.Create () While (true) {try {var total = mq.Total (); if (total > 0) {Console.WriteLine ("number of queues:" + total);} var result = mq.Read () If (result.Body = = null) {continue;} Console.WriteLine (string.Format ("accept queue {0}: {1}", result.Label, result.Body);} catch (Exception ex) {Console.WriteLine ("exception message:" + ex.Message) } catch (Exception ex) {throw ex;} finally {Console.WriteLine ("release.") ; mq.Dispose ();}

Let's run exe to see the effect:

The data that has just joined the queue has been read out. At this time, if we look at the Rabbitmq console, get messages can no longer get the specific content information, because the client consumes the data, and the data in the queue is automatically cleared. As to whether you want to clear the data, this setting is set in the code:

1 var baseResult = channel.BasicGet (name, true); / / true: delete queue after acquisition false: do not delete

The above instructions on code sharing and environment building that encapsulate RabbitMQ, hope to bring you good help. Thank you for reading.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report