RabbitMQ 生產者和消費者C#代碼示例


生產者

static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "192.168.1.102", Password = "guest", UserName = "guest" };

            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                for (int i = 0; i < 3000; i++)
                {
                    channel.QueueDeclare(queue: "test_queue", durable: true, exclusive: false, autoDelete: false, arguments: null);
            //設置每次發送的條數 channel.BasicQos(prefetchSize:
0, prefetchCount: 1, global: false);
            //channel設置為confirm模式 channel.ConfirmSelect();
var body = Encoding.UTF8.GetBytes("abc" + i); var properties = channel.CreateBasicProperties(); properties.Headers = new Dictionary<string, object>(); properties.Headers.Add("name","abc") ; channel.BasicPublish("", "test_queue", properties, body);
            //等待服務端confirm
var issuccess = channel.WaitForConfirms(); } } }

 

消費者

static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "192.168.1.102", Password = "guest", UserName = "guest" };

            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                //聲明隊列
                channel.QueueDeclare("test_queue", true, false, false, null);
          //設置每次接收的條數 channel.BasicQos(
0, 1, false); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, eventArgs) => { var body = Encoding.UTF8.GetString(eventArgs.Body.ToArray()); var headers = eventArgs.BasicProperties.Headers; headers.ToList().ForEach(x => { Console.WriteLine(x.Key + ":::" + Encoding.UTF8.GetString((byte[])x.Value)); }); Console.WriteLine(body); Thread.Sleep(1000); //手動確認,處理完成,告訴Broker可以服務端可以刪除消息,分配新的消息過來 channel.BasicAck(eventArgs.DeliveryTag, false); }; //noAck設置false,告訴broker,發送消息之后,消息暫時不要刪除,等消費者處理完成 channel.BasicConsume("test_queue", false, consumer); Console.WriteLine("按任意件,退出程序"); Console.ReadKey(); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM