发布:2022/1/25 16:06:55作者:管理员 来源:本站 浏览次数:1290
生产者(Producer)
1、创建连接工厂对象(IConnectionFactory)
IConnectionFactory connectionFactory = new ConnectionFactory {
UserName = "ejk5",
Password = "888888",
HostName = "192.168.1.104"
};
2、创建连接对象(IConnection)
using (IConnection connection = connectionFactory.CreateConnection()){
}
3、创建连接会话对象(IModel)
using (IModel channel = connection.CreateModel()) {
}
4、创建或定义消息队列名称(queueName)
5、创建或声明一个队列(QueueDeclare)
channel.QueueDeclare(
queue:queueName,//消息队列名称
durable:false,//是否缓存
exclusive:false,//独家
autoDelete:false,//自动删除
arguments:null//参数
);
6、创建或发送消息(BasicPublish)
while (true) {
Console.WriteLine("请输入消息");
string? message = Console.ReadLine();
if (string.IsNullOrEmpty(message)) {
Console.WriteLine("消息不能为空,请重新输入");
continue;
}
byte[] msg=Encoding.UTF8.GetBytes(message);
#region 7、发送消息
channel.BasicPublish(
exchange:"",
routingKey:queueName,
basicProperties:null,
body:msg
);
Console.WriteLine($"成功发送消息:{message}");
#endregion
}
消费者(Consumer)
1、创建连接工厂对象(IConnectionFactory)
IConnectionFactory connectionFactory = new ConnectionFactory {
UserName = "ejk5",
Password = "888888",
HostName = "192.168.1.104"
};
2、创建连接对象(IConnection)
using (IConnection connection = connectionFactory.CreateConnection()){
3、创建连接会话对象(IModel)
using (IModel channel = connection.CreateModel()) {
4、创建消费者(接收者)对象(queueName)
#region 创建消费者(接收者)对象
//创建消费者对象
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) => {
//等待1秒
//Thread.Sleep(1000);
//随机等待,实现能者多劳
Thread.Sleep((new Random().Next(1, 6)) * 1000);
//接收到的消息
byte[] message=ea.Body.ToArray();
Console.WriteLine($"接收到的信息为:{Encoding.UTF8.GetString(message)}");
//返回消息确认,表示消息已传送到
channel.BasicAck(ea.DeliveryTag,true);
};
#endregion
5、消费者开启监听
channel.BasicConsume(
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4