原文:http://rabbitmq.mr-ping.com/tutorials_with_csharp/HelloWorld.html
1、启动mq;
2、创建C#控制台程序 生产者(product.exe),用nuget引入RabbitMq;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestMq
{
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);
string message = "Hello World! csdn";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
//Console.WriteLine(" Press [enter] to exit.");
//Console.ReadLine();
}
}
}
3、创建消费者C#控制台程序(Consumer.exe),nuget引入rabbitMq:
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestMq_Consumer
{
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();
}
}
}
}
4、编译好后,首先启动product.exe ,则发送了一条消息到mq;然后启动Consumer.exe,则得到了刚才的消息。

本文介绍如何使用C#与RabbitMQ进行消息传递。包括创建生产者和消费者应用程序的具体步骤,通过NuGet安装RabbitMQ客户端,并展示了如何发送与接收消息。
5783

被折叠的 条评论
为什么被折叠?



