1、新建2个控制台项目
image
2、生产者代码
class Program
{ static void Main(string[] args)
{
ConnectionFactory factory = new ConnectionFactory()
{
HostName = "127.0.0.1",
UserName = "guest",
Password = "guest",
}; //第一步:创建connection
var connection = factory.CreateConnection(); //第二步:创建一个channel
var channel = connection.CreateModel(); //第三步:申明交换机【因为rabbitmq已经有了自定义的ampq default exchange】 //第四步:创建一个队列(queue)
channel.QueueDeclare("mytest", true, false, false, null); var msg = Encoding.UTF8.GetBytes("你好"); //第五步:发布消息
channel.BasicPublish(string.Empty, routingKey: "mytest", basicProperties: null, body: msg);
Console.ReadKey();
}
}
3、消费者代码
class Program
{
static void Main(string[] args)
{
ConnectionFactory factory = new ConnectionFactory()
{
HostName = "127.0.0.1",
UserName = "guest",
Password = "guest",
};
//第一步:创建connection
var connection = factory.CreateConnection();
//第二步:创建一个channel
var channel = connection.CreateModel();
//第三步:申明交换机【因为rabbitmq已经有了自定义的ampq default exchange】
//第四步:获取消息
var result = channel.BasicGet("mytest", true);
var msg = Encoding.UTF8.GetString(result.Body);
Console.WriteLine(msg);
Console.ReadKey();
}
}
网友评论