RabbitMQ是一个开源的AMQP实现,服务器端用Erlang语言编写,支持多种客户端,如:Python、Ruby、.NET、Java,也是众多消息队列中表现不俗的一员,做用就是提升系统的并发性,将一些不须要及时响应客户端且占用较多资源的操做,放入队列,再由另一个线程,去异步处理这些队列,可极大的提升系统的并发能力。html
2.使用官网提供的c#操做类库RabbitMQ.Client web
咱们先分别建立两个控制台程序 一个用来发送消息到rabbitmq 消息代理做为何生产者;另一个从中读取进行消费做为消费者。c#
如:p表明生成者,c表明消费者,中间的部分表明消息队列 服务器
生成者的代码以下:并发
public static void RunSend() { ConnectionFactory connectionFactory = new ConnectionFactory() { HostName = "192.168.35.129", Port = 5672, Password = "123", UserName = "mquser" }; //创建链接rabbitmq 消息代理服务器。 using (IConnection conn = connectionFactory.CreateConnection()) { //建立Channel对象 using (IModel channel = conn.CreateModel()) { //声明队列 channel.QueueDeclare("hello", durable: false, exclusive: false, autoDelete: false, arguments: null); //消息 ,此处是简单的字符串,你也能够定义复杂的消息体 string msg = "Hello World"; var body = Encoding.UTF8.GetBytes(msg); //把消息放到队列中 channel.BasicPublish(exchange:"", routingKey:"hello", basicProperties:null, body:body); Console.WriteLine("send {0}",msg); } } }
消费者的代码以下:异步
public static void RunReceive() { ConnectionFactory connectionFactory = new ConnectionFactory() { HostName = "192.168.35.129", Port = 5672, Password = "123", UserName = "mquser" }; using (IConnection conn = connectionFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { //注意:在 send.CS 中也声明了队列Hello,这里为何要再次声明 //第一:QueueDeclare 实现了幂等性,建立的时候若是已经存在,就不会再次建立。 //第二:由于 两边都进行建立,不用考虑 生产者 和消费者 启动的顺序了。 channel.QueueDeclare("hello", durable: false, exclusive: false, autoDelete: false, arguments: null); //建立事件驱动的消费者类型;建议使用此种方式,不要使用while(true) //理由吗 哈哈 看看王清培的博客吧。不稳定不优雅。。。 var consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, e) => { var body = e.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); }; channel.BasicConsume(queue: "hello", noAck: true, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } }
输出spa
好了rabbitmq入门篇讲完了,是否是很简单。线程