RabbitMQ教程(⼆)本地数据交互
⼀、部署好RabbitMQ环境后,我们可以来简单写代码调⽤。创建两个Console程序,分别命名为:RabbitMQ.Server、RabbitMQ.Client
(1)netFreamework需要4.5及以上版本,并且项⽬中要引⽤ RabbitMQ.Client.dll,RabbitMQ.ServiceModel.dll
(2)RabbitMQ.Server,负责发送信息,为⽅便理解,HostName就直接使⽤了localhost
var factory = new RabbitMQ.Client.ConnectionFactory() { HostName = "localhost" };
writeline教程
using (var connection = factory.CreateConnection())//创建Socket连接
{
using (var channel = connection.CreateModel())//channel中包含⼏乎所有的api操作queue
{
//参数含义:队列名、是否持久化、排它性、是否⾃动删除
channel.QueueDeclare(queue: "AllenLeeQueue",//队列名
durable: false,//是否持久化
exclusive: false,//排它性
autoDelete: false,//是否⾃动删除,⼀旦客户端连接断开则⾃动删除queue
arguments: null);////如果安装了队列优先级插件则可以设置优先级
string message = "This morning i want to ";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish("", "AllenLeeQueue", null, body);
Console.WriteLine("AllenLee Sent Msg: {0}", message);
}
}
Console.WriteLine(" Press 【Enter】 to exit.");
Console.ReadLine();
(3)RabbitMQ.Client,负责接收信息,HostName也为localhost
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(
queue: "AllenLeeQueue",//指定发送消息的queue,和⽣产者queue匹配
durable: false,
exclusive: false,
autoDelete: false,
arguments: null
);
var consumer = new EventingBasicConsumer(channel);
string strMsg = "";
//注册接收事件,⼀旦创建连接就去拉取消息
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
strMsg = message;
Console.WriteLine("AllenLee Received: {0}", message);
};
channel.BasicConsume(
queue: "AllenLeeQueue",
noAck: true,//和tcp协议的ack⼀样,为false则服务端必须在收到客户端的回执(ack)后才能删除本条消息
consumer: consumer
);
Console.WriteLine(" Press 【Enter】 to exit.");
Console.ReadLine();
}
(4)运⾏RabbitMQ.Server,RabbitMQ.Client
这两个没有必然的先后执⾏顺序,因为Client会⼀直要侦听检测服务端发来的信息,当Server端⼀旦有信息传来,Client就可以马上Get 到,下图是我先运⾏Client再运⾏Server的情况
(5)当然,也可以把⼀些通⽤变量往前提,看你个⼈爱好
private static ConnectionFactory factory = new ConnectionFactory() { HostName = "localhost" };
⾄此,我们已经完成简单的 RabbitMQ 的使⽤,后续我们继续往深⼊探讨,欢迎⼤家多提宝贵意见,谢谢!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。