发送消息: static ConnectionFactory factory = new ConnectionFactory(); //static IConnection connection = factory.CreateConnection(); //static IModel channel = connection.CreateModel(); static void Main(string[] args) { factory.HostName = "192.168.5.38";//RabbitMQ服务在本地运行 factory.UserName = "guest";//用户名 factory.Password = "guest";//密码 for (int i = 0; i < 100; i++) { Thread t = new Thread(new ThreadStart(a)); t.Start(); Console.WriteLine(i.ToString()); } // var factory = new ConnectionFactory(); using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare("test", false, false, false, null);//创建一个名称为test的消息队列 string message = "testaaaaaa"; //传递的消息内容 var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish("", "test", null, body); //开始传递 Console.WriteLine("已发送: {0}", message); Console.ReadLine(); } } } static void a() { for (int i = 0; i < 1000; i++) { using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare("test", false, false, false, null);//创建一个名称为test的消息队列 string message = "Hello World1 "+i; //传递的消息内容 var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish("", "test", null, body); //开始传递 Console.WriteLine("已发送: {0}", message); } } } }
接收消息: static void Main(string[] args) { var factory = new ConnectionFactory() { HostName = "192.168.5.38" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "test", durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine("接收 {0}", message); }; channel.BasicConsume(queue: "test", noAck: true, consumer: consumer); Console.ReadLine(); } }