c# simply call rabbitmq

If you have not installed rabbitmq, you can refer to the link below

https://www.cnblogs.com/kiba/p/11703073.html

If you want to quickly get the entire rabbitmq installation package, just follow my public account "Ink Direct" and reply "rabbitmq download" to get it

sender:

 static void Main(string[] args)
        {
            var factory = new ConnectionFactory();
            factory.HostName = "xxx.xxx.xxx.xx";
            factory.UserName = "xxx";
            factory.Password = "xxxxx";
            using (var connection = factory.CreateConnection())//连接服务器,即正在创建终结点。
            {
                //创建一个通道,这个就是Rabbit自己定义的规则了,如果自己写消息队列,这个就可以开脑洞设计了
                //这里Rabbit的玩法就是一个通道channel下包含多个队列Queue
                using (var channel = connection.CreateModel())
                {
                    for (int i = 0; i < 100; i++)
                    {
                        channel.QueueDeclare("kibaQueue", false, false, false, null);//创建一个名称为kibaQueue的消息队列
                        var properties = channel.CreateBasicProperties();
                        properties.DeliveryMode = 1;
                        string message = "I am Kiba518"; //传递的消息内容 
                        channel.BasicPublish("", "kibaQueue", properties, Encoding.UTF8.GetBytes(message)); //生产消息
                        Console.WriteLine($"Send:{message}");
                        Thread.Sleep(3000);
                    }
                }
            }
            Console.ReadLine();
        }

receiver:

 static void Main(string[] args)
        {
            var factory = new ConnectionFactory();
            factory.HostName = "xxx.xx.xxx.xx";
            factory.UserName = "xxx";
            factory.Password = "xxxxx";

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare("kibaQueue", false, false, false, null);
                    var consumer = new EventingBasicConsumer(channel);//消费者 
                    channel.BasicConsume("kibaQueue", true, consumer);//消费消息 autoAck参数为消费后是否删除
                    consumer.Received += (model, ea) =>
                    {
                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine("Received: {0}", message);
                    };
                    Console.ReadLine();
                }
            }
        }

Interested friends can also follow my official account! There are various programming resources to receive for free

Guess you like

Origin blog.csdn.net/huxinyu0208/article/details/108620857