RabbitMQ消息发布/订阅
作者:佚名 发表时间:2019-08-16 15:06:17
  /// <summary>
        /// 连接配置
        /// </summary>
        private static readonly ConnectionFactory rabbitMqFactory = new ConnectionFactory()
        {
            HostName = "172.18.0.88",
            UserName = "admin",
            Password = "admin123",
            Port = 5673,
            VirtualHost = "order"
        };
        //队列名称
        const string exchange = "yujiajun";
        const string queueName = "auth";
 /// <summary>
        ///  发送
        /// </summary>
        public static void SendMsg()
        {
            using (IConnection conn = rabbitMqFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    channel.ExchangeDeclare(exchange: exchange, type: "fanout");//fanout 模式
                    int i = 0;
                    while (true)
                    {
                        Thread.Sleep(1000);
                        i++;
                        var message = "yujiajun" + i.ToString();
                        var body = Encoding.UTF8.GetBytes(message);
                        channel.BasicPublish(exchange: exchange,
                                             routingKey: "",
                                             basicProperties: null,
                                             body: body);
                        Console.WriteLine(" [x] Sent {0}", message);
                    }
                }
            }
        }
/// <summary>
        /// 订阅
        /// </summary>
        public static void ReadMsg()
        {
            rabbitMqFactory.AutomaticRecoveryEnabled = true;//自动重连
            IConnection connection = rabbitMqFactory.CreateConnection();
            IModel channel = connection.CreateModel();

            channel.ExchangeDeclare(exchange, "fanout");//fanout模式
            string _queueName = channel.QueueDeclare().QueueName;

            channel.QueueBind(_queueName, exchange, "");
            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += (model, ea) =>
              {
                  var body = ea.Body;
                  var message = Encoding.UTF8.GetString(body);
                  if (!string.IsNullOrWhiteSpace(message))
                  {
                      Console.WriteLine(message);
                  }
              };
            channel.BasicConsume(_queueName, true, consumer);
            Console.ReadLine();
        }