RabbitMQ .NET消息队列使用入门【简单示例】
首先下载安装包,我都环境是win7 64位:
去官网下载 otp_win64_19.0.exe 和rabbitmq-server-3.6.3.exe安装好
然后开始编程了:
(1)创建生产者类:
- class Program
- {
- private static void Main()
- {
-
- var connectionFactory = new ConnectionFactory
- {
- HostName = "127.0.0.1",
- Port = 5672,
- UserName = "guest",
- Password = "guest",
- Protocol = Protocols.DefaultProtocol,
- AutomaticRecoveryEnabled = true,
- RequestedFrameMax = UInt32.MaxValue,
- RequestedHeartbeat = UInt16.MaxValue
- };
- try
- {
- using (var connection = connectionFactory.CreateConnection())
- {
- using (var channel = connection.CreateModel())
- {
-
- channel.ExchangeDeclare("SISOExchange", ExchangeType.Direct, true, false, null);
-
- channel.QueueDeclare("SISOqueue", true, false, false, null);
-
- channel.QueueBind("SISOqueue", "SISOExchange", "optionalRoutingKey");
-
-
- var properties = channel.CreateBasicProperties();
- properties.DeliveryMode = 2;
-
-
-
- var encoding = new UTF8Encoding();
- for (var i = 0; i < 10; i++)
- {
- var msg = string.Format("这是消息 #{0}?", i + 1);
- var msgBytes = encoding.GetBytes(msg);
-
-
-
-
-
- channel.BasicPublish("SISOExchange", "optionalRoutingKey", properties, msgBytes);
- }
- channel.Close();
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
-
- Console.WriteLine("消息发布!");
- Console.ReadKey(true);
- }
- }
(2)创建消费者类:
- class Program
- {
- private static void Main()
- {
-
- var connectionFactory = new ConnectionFactory
- {
- HostName = "127.0.0.1",
- Port = 5672,
- UserName = "guest",
- Password = "guest",
- Protocol = Protocols.AMQP_0_9_1,
- RequestedFrameMax = UInt32.MaxValue,
- RequestedHeartbeat = UInt16.MaxValue
- };
-
- using (var connection = connectionFactory.CreateConnection())
- using (var channel = connection.CreateModel())
- {
-
- channel.BasicQos(0, 1, false);
-
-
- channel.ExchangeDeclare("SISOExchange", ExchangeType.Direct, true, false, null);
-
- channel.QueueDeclare("sample-queue", true, false, false, null);
-
- channel.QueueBind("SISOqueue", "SISOExchange", "optionalRoutingKey");
- using (var subscription = new Subscription(channel, "SISOqueue", false))
- {
- Console.WriteLine("等待消息...");
- var encoding = new UTF8Encoding();
- while (channel.IsOpen)
- {
- BasicDeliverEventArgs eventArgs;
- var success = subscription.Next(2000, out eventArgs);
- if (success == false) continue;
- var msgBytes = eventArgs.Body;
- var message = encoding.GetString(msgBytes);
- Console.WriteLine(message);
- channel.BasicAck(eventArgs.DeliveryTag, false);
- }
- }
- }
- }
- }
消费者--结果如图:
原文地址