1.安裝Erlang Windows Binary Filehtml
2.安裝rabbitmq-server(windows)rabbitmq-server-3.5.4.exewindows
參考:http://www.rabbitmq.com/install-windows.htmlide
sendMessage code:spa
1 var factory = new ConnectionFactory() { HostName = "localhost" }; 2 using (var connection = factory.CreateConnection()) 3 { 4 using (var channel = connection.CreateModel()) 5 { 6 channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); 7 string message = "你好 mq!"; 8 var body = Encoding.UTF8.GetBytes(message); 9 channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body); 10 Console.WriteLine(string.Format("發送消息:{0}", message)); 11 Console.ReadLine(); 12 } 13 }
receiveMessage code:code
1 var factory = new ConnectionFactory() { HostName="localhost"}; 2 using (var connection=factory.CreateConnection()) 3 { 4 using (var channel=connection.CreateModel()) 5 { 6 channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); 7 8 var consumer = new EventingBasicConsumer(channel); 9 consumer.Received += (model, ea) => 10 { 11 var body = ea.Body; 12 string message = Encoding.UTF8.GetString(body); 13 Console.WriteLine(string.Format("接收消息:{0}", message)); 14 }; 15 channel.BasicConsume(queue: "hello", noAck: true, consumer: consumer); 16 17 Console.WriteLine("結束!"); 18 Console.ReadLine(); 19 } 20 }
具體項目中應用,都會用到開源的定義EasyNetQ(經過Nuget Packages得到http://easynetq.com/)orm
參考用法:server
public class MqProvider { private static readonly MqProvider provider = new MqProvider(); private static readonly string mqconnstr = "localhost"; private static readonly IBus bus; private static readonly IExchange exchange; private static readonly int RedisCacheTimeSpan; private MqProvider() { } public static MqProvider Instance { get { return provider; } } static MqProvider() { bus = RabbitHutch.CreateBus(mqconnstr); exchange = bus.Advanced.ExchangeDeclare("my-exchange", "topic"); IQueue queue = bus.Advanced.QueueDeclare("my-queue "); bus.Advanced.Bind(exchange, queue, "rote-key"); } public bool Test() { return bus != null && exchange != null; } public void SendMessage(string message) { bus.Advanced.PublishAsync<string>(exchange, "rote-key", false, false, new Message<string>(message)); } }