RabbitMQ的应用
1.安装
如果有Docker,可以通过Docker来安装,命令:
docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management
启动后,查看端口:
查看是否安装好,在浏览器中用15672端口进行查看。
能出现这个就说明安装成功。
用户名和密码初始都是guest。
登录成功后:
也可以从下面的页面直接下载:https://www.rabbitmq.com/install-windows.html
对应的是这两个链接:
https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.8.9/rabbitmq-server-3.8.9.exe
https://dl.bintray.com/rabbitmq/all/rabbitmq-server/3.8.9/rabbitmq-server-3.8.9.exe
2.开发
开发之前先看看入门文档: https://www.rabbitmq.com/getstarted.html
命令行方式:
dotnet new console --name Send
move Send/Program.cs Send/Send.cs//在Powershell下用mv 命令,cmd下用Move命令。
dotnet new console --name Receive
move Receive/Program.cs Receive/Receive.cs //在Powershell下用mv 命令,cmd下用Move命令。
cd Send
dotnet add package RabbitMQ.Client
dotnet restore
cd ../Receive
dotnet add package RabbitMQ.Client
dotnet restore
visual studio 2019 方式:
用.net core 创建程序
NuGet安装:
安装后:
代码参考: https://github.com/rabbitmq/rabbitmq-tutorials/tree/master/dotnet
发送端源码:
using System;
using RabbitMQ.Client;
using System.Text;
using System.Threading;
namespace Send
{
class Program
{
static void Main(string[] args)
{
for(int i=0;i<10;i++){
var factory=new ConnectionFactory(){ HostName="localhost"};
using(var connection=factory.CreateConnection()){
using(var channel=connection.CreateModel()){
channel.QueueDeclare(queue:"hello",durable:false,exclusive:false,autoDelete:false,arguments:null);
string message="Hello World "+ i.ToString();
var body=Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange:"",routingKey:"hello",basicProperties:null,body:body);
Console.WriteLine(" [x] Sent {0}",message);
}
}
Thread.Sleep(1000);
}
Console.WriteLine(" Press [Enter] to exit.");
Console.ReadLine();
}
}
}
接收端源码:
using System;
using RabbitMQ.Client;
using System.Text;
using RabbitMQ.Client.Events;
namespace Receive
{
class Program
{
static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
}
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
以上只是简单的实现了发送和接收。接下来是更复杂些的。