码迷,mamicode.com
首页 > 其他好文 > 详细

RabbitMQ 使用demo

时间:2017-06-01 19:41:03      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:point   utf8   hostname   amqp   bit   技术分享   客户端   tostring   ann   

1.新建一个控制台应用程序:如图

技术分享

 

2.代码如下:

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MQ
{
class Program
{
static void Main(string[] args)
{
string type = Console.ReadLine();
//生产者
if (type == "1")
{
ConnectionFactory factory = new ConnectionFactory();
factory.HostName = "192.168.2.24";
factory.UserName = "zhangweizhong";
factory.Password = "weizhong1988";
factory.VirtualHost = "orderqueue";
//注意host默认为5672
//factory.UserName = "admin";
//factory.Password = "123456";
//factory.VirtualHost = "adminhost";
//factory.Endpoint = new AmqpTcpEndpoint("localhost");
//默认端口
using (IConnection conn = factory.CreateConnection())
{
using (IModel channel = conn.CreateModel())
{
//在MQ上定义一个持久化队列,如果名称相同不会重复创建
channel.QueueDeclare("orderqueue", true, false, false, null);
while (true)
{
string message = string.Format("Message_{0}", Console.ReadLine());
byte[] buffer = Encoding.UTF8.GetBytes(message);
IBasicProperties properties = channel.CreateBasicProperties();
properties.DeliveryMode = 2;
channel.BasicPublish("", "orderqueue", properties, buffer);
Console.WriteLine("消息发送成功:" + message);
}
}
}
}
else
{
//消费者
ConnectionFactory factory = new ConnectionFactory();
factory.HostName = "192.168.2.24";
factory.UserName = "zhangweizhong";
factory.Password = "weizhong1988";
factory.VirtualHost = "orderqueue";
using (IConnection conn = factory.CreateConnection())
{
using (IModel channel = conn.CreateModel())
{
//在MQ上定义一个持久化队列,如果名称相同不会重复创建
channel.QueueDeclare("orderqueue", true, false, false, null);

//输入1,那如果接收一个消息,但是没有应答,则客户端不会收到下一个消息
channel.BasicQos(0, 1, false);

Console.WriteLine("Listening...");

//在队列上定义一个消费者
QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel);
//消费队列,并设置应答模式为程序主动应答
channel.BasicConsume("orderqueue", false, consumer);

while (true)
{
//阻塞函数,获取队列中的消息
BasicDeliverEventArgs ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
byte[] bytes = ea.Body;
string str = Encoding.UTF8.GetString(bytes);

Console.WriteLine("队列消息:" + str.ToString());
//回复确认
channel.BasicAck(ea.DeliveryTag, false);
}
}
}
}
}
}
}

  

 

 

踩过的坑:(备注)

1.RabbitMQ默认端口为:5672

2.引用的第三方组件:RabbitMQ.Client

 

需要了解RabbitMQ的安装部署可查阅本博客RabbitMQ安装篇章!!!

RabbitMQ 使用demo

标签:point   utf8   hostname   amqp   bit   技术分享   客户端   tostring   ann   

原文地址:http://www.cnblogs.com/yczzw/p/6930322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!