Raiitmq分布式消息队列分发机制(c#)
切身体会到消息队列的好用,rabiitmq采用排队消费,数据会及时传到rabiitmq server上
下面我们来定义生产者一号
public static void Main(string[] args) { var factory = new ConnectionFactory(); factory.HostName = "localhost";//RabbitMQ服务在本地运行 factory.UserName = "guest";//用户名 factory.Password = "guest";//密码 using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare("hello rabiitmq", true, false, false, null);//创建一个名称为hello的消息队列 //int prefetchCount = 1; //每个消费者发送确认信号之前,消息队列不发送下一个消息过来,一次只处理一个消息 //限制发给同一个消费者不得超过1条消息 channel.BasicQos(0, 1, false); // 发送的消息 for (int i = 0; i < 50; i++) { String message = "生产者一号生产消息" + i; // 往队列中发出一条消息 channel.BasicPublish("", "hello rabiitmq", null, Encoding.UTF8.GetBytes(message)); Console.WriteLine("队列生产 '" + message + "次'"); Thread.Sleep(i * 10); } // 关闭频道和连接 channel.Close(); connection.Close(); } } Console.ReadKey();
下面我们来定义生产者二号
public static void Main(string[] args) { var factory = new ConnectionFactory(); factory.HostName = "localhost";//RabbitMQ服务在本地运行 factory.UserName = "guest";//用户名 factory.Password = "guest";//密码 using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare("hello rabiitmq", true, false, false, null);//创建一个名称为hello的消息队列 //int prefetchCount = 1; //每个消费者发送确认信号之前,消息队列不发送下一个消息过来,一次只处理一个消息 //限制发给同一个消费者不得超过1条消息 channel.BasicQos(0, 1, false); // 发送的消息 for (int i = 0; i < 50; i++) { String message = "生产者二号生产消息" + i; // 往队列中发出一条消息 channel.BasicPublish("", "hello rabiitmq", null, Encoding.UTF8.GetBytes(message)); Console.WriteLine("队列生产 '" + message + "次'"); Thread.Sleep(i * 20); } // 关闭频道和连接 channel.Close(); connection.Close(); } } Console.ReadKey();
下面我们来定义消费者
public static void Main(string[] args) { var factory = new ConnectionFactory(); factory.HostName = "localhost"; factory.UserName = "guest"; factory.Password = "guest"; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare("hello rabiitmq", true, false, false, null); channel.BasicQos(0, 1, false); var consumer = new QueueingBasicConsumer(channel); channel.BasicConsume("hello rabiitmq", false, consumer); while (true) { var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue(); var body = ea.Body; var message = Encoding.UTF8.GetString(body); int dots = message.Split('.').Length - 1; Thread.Sleep(dots * 1000); Console.WriteLine("消费者成功接收消息 {0}", message); Console.WriteLine("End"); channel.BasicAck(ea.DeliveryTag, false); } Boolean autoAck = false; //手动确认消息 channel.BasicConsume("hello rabiitmq", autoAck, consumer); } } }
分别执行后
自己记录一下,慢慢发现编程乐趣。