如何在.net核心网站中使用Rabbitmq

时间:2019-08-19 12:37:42

标签: web rabbitmq

顾名思义,官方网站上的示例是控制台项目,但真的不可能应用于asp.net核心网站吗? 我的Web项目作为使用者或生产者,但不输出接收到的信息,但是rabbitmq页面控制台显示已发送的队列消息,那么实际生产环境中的使用者或生产者是什么?Windows服务器?控制台? 这是我的api代码:

[HttpGet]
        public ActionResult sendMgs()
        {
            string message = string.Empty;
            //var uri = new Uri("amqp://192.168.150.129:5672");
            var factory = new ConnectionFactory()
            {
                UserName = "admin",
                Password = "admin",
                Port=5672,
                HostName= "192.168.150.129",
                RequestedHeartbeat = 0,
                VirtualHost= "/vhost_mmr"
                //Endpoint = new AmqpTcpEndpoint(uri)
            };

            using (var connection=factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue:"hello",
                                         durable:false,
                                         exclusive:false,
                                         autoDelete:false,
                                         arguments:null);
                    message = "Hello World";
                    var body = Encoding.UTF8.GetBytes(message);
                    channel.BasicPublish(exchange: "",
                                         routingKey:"hello",
                                         basicProperties:null,
                                         body:body);

                }
            }
            return Json(new {message = message });
        }

这是我的mvc网络代码:

public IActionResult MqTest()
        {
            System.Diagnostics.Debug.Write("test begin:");
            GetQueueMsg();
            return View();
        }
 public void GetQueueMsg()
        {
            var factory = new ConnectionFactory()
            {
                UserName = "admin",
                Password = "admin",
                Port = 5672,
                HostName = "192.168.150.129",
                RequestedHeartbeat = 0,
                VirtualHost = "/vhost_mmr"
            };
            using (var connection = factory.CreateConnection())
            {
                using (var channel =connection.CreateModel())
                {
                    var consumer = new EventingBasicConsumer(channel);
                     consumer.Received +=  (model, ea) =>
                    {
                        var body = ea.Body;
                        var msg = Encoding.UTF8.GetString(body);
                        ViewBag.msg = msg;
                        System.Diagnostics.Debug.Write("test:" + msg);
                    };

                    var ret = channel.BasicConsume(queue: "hello",
                                         autoAck: true,
                                         consumer: consumer);
                }
            }
        }

0 个答案:

没有答案