今天收获不少,记个笔记。
1 namespace RabbitMQTest 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Consumer(); 8 //Console.WriteLine("方法————{0}",Thread.CurrentThread.ManagedThreadId); 9 10 //Thread thread = new Thread(Consumer); 11 //thread.Start(); 12 //Console.WriteLine("线程1————{0}", Thread.CurrentThread.ManagedThreadId); 13 //Thread tt = new Thread( 14 // () => { 15 // Consumer(); 16 // } 17 // ); 18 //tt.Start(); 19 20 Task task = new Task(Consumer); 21 task.Start(); 22 23 TaskFactory tf = new TaskFactory(); 24 Task t = tf.StartNew(Consumer); 25 //Console.WriteLine("线程2————{0}", Thread.CurrentThread.ManagedThreadId); 26 Console.ReadLine(); 27 } 28 29 private static void Consumer() 30 { 31 Console.WriteLine("线程开始,ID:" + Thread.CurrentThread.ManagedThreadId); 32 var factory = new ConnectionFactory() { HostName = "localhost" }; 33 using (var connection = factory.CreateConnection()) 34 using (var channel = connection.CreateModel()) 35 { 36 //声明queue 37 channel.QueueDeclare(queue: "hellos",//队列名 38 durable: false,//是否持久化 39 exclusive: false,//true:排他性,该队列仅对首次申明它的连接可见,并在连接断开时自动删除 40 autoDelete: false,//true:如果该队列没有任何订阅的消费者的话,该队列会被自动删除 41 arguments: null);//如果安装了队列优先级插件则可以设置优先级 42 43 string message = "Hello World!";//待发送的消息 44 var body = Encoding.UTF8.GetBytes(message); 45 for (int i = 0; i < 5; i++) 46 { 47 channel.BasicPublish(exchange: "",//exchange名称 48 routingKey: "hellos",//如果存在exchange,则消息被发送到名称为hello的queue的客户端 49 basicProperties: null, 50 body: body);//消息体 51 Console.WriteLine(" [x] Sent {0}", message); 52 } 53 } 54 } 55 } 56 }
1 namespace RabbitXiaoFei 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 //var factory = new ConnectionFactory() { HostName = "localhost", UserName = "ty2017", Password = "123456", VirtualHost = "log" }; 8 var factory = new ConnectionFactory() { HostName = "localhost" }; 9 using (var connection = factory.CreateConnection()) 10 using (var channel = connection.CreateModel()) 11 { 12 channel.QueueDeclare(queue: "hellos",//指定发送消息的queue,和生产者的queue匹配 13 durable: false,//耐用的,持久的 14 exclusive: false,//独有的;排外的;专一的 15 autoDelete: false,// 16 arguments: null); 17 18 //设置预取消息的数量为1个,消费完当前的消息后再去获取下一个消息 19 //就是有多个消费者去请求队列的时候,序号为奇数的会给第一个,为偶数的会给第二个 20 //但是如果第一个要耗费很长时间,那么第二个就得等,那就很消耗资源了 21 //要是每个Consumer处理完一个消息后再去获取下一个消息,这是多么理想呀! 22 channel.BasicQos(0, //设置0 23 1, //设置当前Consumer的预取数量为1个就行啦! 24 false); //设置false 25 26 var consumer = new EventingBasicConsumer(channel); 27 //注册接收事件,一旦创建连接就去拉取消息 28 consumer.Received += (obj, sss) => 29 { 30 var body = sss.Body; 31 var message = Encoding.UTF8.GetString(body); 32 Console.WriteLine(" [x] Received {0}", message); 33 }; 34 channel.BasicConsume(queue: "hellos", 35 autoAck:true,//Ack :确认 36 //和tcp协议的ack一样,为false则服务端必须在收到客户端的回执(ack)后才能删除本条消息 37 consumer: consumer); 38 Console.WriteLine(" Press [enter] to exit."); 39 Console.ReadLine(); 40 } 41 } 42 } 43 }