版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013938578/article/details/81700670
Producter 发送消息代码:
/// <summary>
/// 连接配置
/// </summary>
private static readonly ConnectionFactory rabbitMqFactory = new ConnectionFactory(){
HostName ="192.168.1.8",UserName="hao",Password="abc123",Port= 5672
};
/// <summary>
/// 路由名称
/// </summary>
const string TopExchangeName = "topic.justin.exchange";
//队列名称
const string TopQueueName = "topic.justin.queue";
public static void TopicExchangeSendMsg()
{
using (IConnection conn = rabbitMqFactory.CreateConnection())
{
using (IModel channel = conn.CreateModel())
{
channel.ExchangeDeclare(TopExchangeName, "topic", durable: false, autoDelete: false, arguments: null);
channel.QueueDeclare(TopQueueName, durable: false, autoDelete: false, exclusive: false, arguments: null);
channel.QueueBind(TopQueueName, TopExchangeName, routingKey: TopQueueName);
//var props = channel.CreateBasicProperties();
//props.Persistent = true;
string vadata = Console.ReadLine();
while (vadata != "exit")
{
var msgBody = Encoding.UTF8.GetBytes(vadata);
channel.BasicPublish(exchange: TopExchangeName, routingKey: TopQueueName, basicProperties: null, body: msgBody);
Console.WriteLine(string.Format("***发送时间:{0},发送完成,输入exit退出消息发送", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
vadata = Console.ReadLine();
}
}
}
}
Customer接收消息代码:
/// <summary>
/// 连接配置
/// </summary>
private static readonly ConnectionFactory rabbitMqFactory = new ConnectionFactory() {
HostName = "192.168.1.8", UserName = "hao", Password = "abc123", Port = 5672
};
/// <summary>
/// 路由名称
/// </summary>
const string TopExchangeName = "topic.justin.exchange";
//队列名称
const string TopQueueName = "topic.justin.queue";
public static void TopicAcceptExchange()
{
using (IConnection conn = rabbitMqFactory.CreateConnection())
{
using (IModel channel = conn.CreateModel())
{
channel.ExchangeDeclare(TopExchangeName, "topic", durable: false, autoDelete: false, arguments: null);
channel.QueueDeclare(TopQueueName, durable: false, autoDelete: false, exclusive: false, arguments: null);
channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
channel.QueueBind(TopQueueName, TopExchangeName, routingKey: TopQueueName);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var msgBody = Encoding.UTF8.GetString(ea.Body);
Console.WriteLine(string.Format("***接收时间:{0},消息内容:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msgBody));
int dots = msgBody.Split('.').Length - 1;
System.Threading.Thread.Sleep(dots * 1000);
Console.WriteLine(" [x] Done");
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};
channel.BasicConsume(TopQueueName, noAck: false, consumer: consumer);
Console.WriteLine("按任意值,退出程序");
Console.ReadKey();
}
}
}