Bright Leopold

i come from the other world,i will go back after the love,the regret,the alive and the dead are over

导航

rabbitmq (一)用法

首先,主机一是window系统,虚拟机二 ubuntu,

ubuntu部署了rabbitmq服务端.默认监听5672端口.

由于rabbitmq内部有严格的权限系统,使用之前必须配置好权限.

默认网页是不允许访问的,需要增加一个用户修改一下权限,代码如下:

 添加用户:rabbitmqctl add_user wc wc

 添加权限:rabbitmqctl set_permissions -p "/" wc ".*" ".*" ".*"

     修改用户角色rabbitmqctl set_user_tags wc administrator

 然后就可以远程访问了,然后可直接配置用户权限等信息。

 

使用C#编写 消费者和生产者

首先使用nuget获取rabbitmq.

生产者代码:

using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RMQ_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "rabbitmq server ip", UserName = "wc", Password = "wc" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //定义队列(hello为队列名)
                    channel.QueueDeclare("hello", false, false, false, null);
                    //发送到队列的消息,包含时间戳
                    string message = "Hello World!" + "_" + DateTime.Now.ToString();
                    var body = Encoding.UTF8.GetBytes(message);
                    channel.BasicPublish("", "hello", null, body);
                    Console.WriteLine(" [x] Sent {0}", message);
                }
            }
        }
    }
}

消费者代码:

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

namespace RMQ_Server
{
    class Program
    {
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "rabbitmq server ip", UserName = "wc", Password = "wc" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //定义队列(hello为队列名)
                    channel.QueueDeclare("hello", false, false, false, null);

                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume("hello", true, consumer);

                    Console.WriteLine(" [*] Waiting for messages." +
                                             "To exit press CTRL+C");
                    while (true)
                    {
                        //接受客户端发送的消息并打印出来
                        var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received {0}", message);
                    }
                }
            }
        }
    }
}

 

posted on 2017-12-19 17:16  Bright Leopold  阅读(114)  评论(0编辑  收藏  举报