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

RabbitMQ 学习初步(一)

时间:2014-12-20 23:35:49      阅读:382      评论:0      收藏:0      [点我收藏+]

标签:

        //刚刚接触,如有不对还望不吝指正
        public static void StartUp()
        {
            #region 前期准备工作

            ConnectionFactory factory = new ConnectionFactory();
            factory.Uri = "amqp://guest:guest@localhost:5672/";
            //架起物理链路
            IConnection conn = factory.CreateConnection();
            //创建通信信道
            IModel channel = conn.CreateModel();

            string exchangename = "我是负责转发信号的路由1";
            string queuename = "我是信号的接收器1";
            //架设信号路由
            channel.ExchangeDeclare(exchangename, ExchangeType.Direct);
            //架设信号接收器
            channel.QueueDeclare(queuename, false, false, false, null);
            //连通信号路由器和接收器
            channel.QueueBind(queuename, exchangename, "", null);

            #endregion

            byte[] messageBodyBytes = System.Text.Encoding.UTF8.GetBytes("Hello, world!");
            //channel.BasicPublish(exchangename,"",null,messageBodyBytes);
            IBasicProperties props = channel.CreateBasicProperties();
            props.ContentType = "text/plain";
            props.DeliveryMode = 2;
            channel.BasicPublish(exchangename,"",props,messageBodyBytes);


            ConnectionFactory service = new ConnectionFactory();

            using (conn = service.CreateConnection())
            {
                using (IModel servicechannle = conn.CreateModel())
                {
                    //ch.QueueDeclare(queuename, false, false, false, null);
                    //服务端接收消息队列
                    bool noAck = false;
                    BasicGetResult result = servicechannle.BasicGet(queuename, noAck);
                    if (result == null)
                    {
                        Console.WriteLine("没有消息");
                    }
                    else
                    {
                        servicechannle.BasicAck(result.DeliveryTag, false);
                        Console.WriteLine("接收消息成功:" + result.BasicProperties.ContentType);
                        Console.WriteLine("接收消息成功:" + result.BasicProperties.DeliveryMode);
                        Console.WriteLine("接收消息成功:" + System.Text.Encoding.Default.GetString(result.Body));
                    }
                }
            }


            conn.AutoClose = true;
        }


RabbitMQ 学习初步(一)

标签:

原文地址:http://my.oschina.net/osenlin/blog/358752

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