send hello之rabbitMQ
1、发送信息
static void Main(string[] args) { while (true) { string message = Console.ReadLine(); if (!string.IsNullOrWhiteSpace(message)) { SendMessage(message); } } } static void SendMessage(string message1) { var factory = new RabbitMQ.Client.ConnectionFactory(); factory.HostName = "localhost"; factory.UserName = "mqtest"; factory.Password = "123456"; factory.VirtualHost = "vhTest1"; using (IConnection conn = factory.CreateConnection()) using (IModel channel = conn.CreateModel()) { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); string message = message1;// "Hello World"; var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body); Console.WriteLine(" set{0}", message); } }
2、接收消息
var factory = new ConnectionFactory(); factory.HostName = ConfigurationManager.AppSettings["mqHostName"]; //"localhost"; factory.UserName = "mqtest"; factory.Password = "123456"; factory.VirtualHost = "vhTest1"; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { //channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); //var consumer = new EventingBasicConsumer(channel); //channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer); //consumer.Received += (model, ea) => //{ // var body = ea.Body; // string message = Encoding.UTF8.GetString(body); // Console.WriteLine("{x} received {0}", message); //}; while (true) { BasicGetResult res = channel.BasicGet(queue: "hello", autoAck: true); if (res != null) { var body = res.Body; var message = Encoding.UTF8.GetString(res.Body); Task.Run(() => { Console.WriteLine("receiver:{0},message:{1}", Thread.CurrentThread.ManagedThreadId.ToString(), message); }); } } }

浙公网安备 33010602011771号