C# RabbitMQ 基本使用
public class RabbitMQHelper { ConnectionFactory factory = null; IConnection connection = null; IModel channel = null; public RabbitMQHelper(string host, string username, string password) { factory = new ConnectionFactory() { HostName = host, UserName = username, Password = password }; } public RabbitMQHelper() { factory = new ConnectionFactory() { HostName = "localhost", UserName = "Jason", Password = "hensuiyi" }; connection = factory.CreateConnection(); channel = connection.CreateModel(); } const string queueName = "my_queue"; const string exchangeName = "my_exchange"; const string routeName = "my_route"; /// <summary> /// 接收消息 执行回调 /// </summary> /// <param name="callback"></param> public void Receive(Action<string> callback) { channel.ExchangeDeclare(exchangeName, ExchangeType.Direct, true, false, null); channel.QueueDeclare(queueName, true, false, false, null); channel.QueueBind(queueName, exchangeName, routeName, null); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { ReadOnlyMemory<byte> body = ea.Body; var message = System.Text.Encoding.UTF8.GetString(body.ToArray()); callback(message); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queueName, autoAck: false, consumer: consumer); } public void Send(string content) { channel.ExchangeDeclare(exchangeName, ExchangeType.Direct, true, false, null); channel.QueueDeclare(queueName, true, false, false, null); channel.QueueBind(queueName, exchangeName, routeName, null); var properties = channel.CreateBasicProperties(); properties.Persistent = true; properties.DeliveryMode = 1; byte[] body = Encoding.UTF8.GetBytes(content); //开始发送 channel.BasicPublish(exchangeName, routeName, properties, body); } }
关于 Exchange Route Queue 的关系: https://www.cnblogs.com/linkenpark/p/5393666.html