c# rabbitmq 创建交换机+创建列队+列队绑定交换机+监听消息队列

需要引用:rabbitmq.client包

        var factory = new ConnectionFactory()
            {
                HostName = "192.168.75.129",
                UserName = "admin",
                Password = "123456",
            };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //创建交换机
                    channel.ExchangeDeclare("net.exchange", "fanout");
                    //创建列队
                    //durable:持久化
                    //exclusive:排外
                    // 当前定义的队列是connection中的chanenl是共享的,其他的connection是访问不到的;
                    // 当connection.close时,queue就被删除。
                    //autoDelete:自动删除:当最后一个consumer断开之后,autodelete被触发;
                    channel.QueueDeclare(queue:"net.queue",false,false,autoDelete:false);
                    //列队绑定交换机
                    channel.QueueBind("net.queue", "net.exchange", "net.run.key");
                    //声明事件对象
                    var consumer = new EventingBasicConsumer(channel);
                    //声明列队消息事件
                    consumer.Received += (model, ea) =>
                    {
                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body.ToArray());
                        Console.WriteLine("net 收到消息{0}", message);
                    };
                    //事件注册注册到channel里
                    channel.BasicConsume(queue: "net.queue",
                                         autoAck: true,
                                         consumer: consumer);
                    //发送消息
                    var body = Encoding.UTF8.GetBytes("ello World");
                    channel.BasicPublish("net.exchange", "net.run.key", null, body);
                    Console.WriteLine("按回车退出");

                    Console.ReadLine();
                }
            }

 

posted @ 2022-10-04 17:27  lzy1666  阅读(87)  评论(0编辑  收藏  举报