RabbitMQ C#程序示例
2021/12/28 11:08:06
本文主要是介绍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.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); 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(); } }
这篇关于RabbitMQ C#程序示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#