private void btnHeadersPublish_Click(object sender, EventArgs e)
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare("myHeadersExchange1", ExchangeType.Headers, true, false, null);
channel.QueueDeclare("headers_queue1", true, false, false, null);
channel.QueueBind("headers_queue1", "myHeadersExchange1", string.Empty, new Dictionary<string, object>() {
{"x-match","all" },//any
{ "username","fan"},
{ "password","123456"}
});
//properties
var properties = channel.CreateBasicProperties();
properties.Headers = new Dictionary<string, object>();
properties.Headers.Add("username", "fan");
properties.Headers.Add("password", "123456");
properties.Persistent = true;//消息持久化
//发布info消息
for (int i = 0; i < 100; i++)
{
var msg = Encoding.UTF8.GetBytes($"{i}:haha");
channel.BasicPublish("myHeadersExchange1", string.Empty, properties, msg);
}
}
}
Demo2.消费消息两种方式
/// <summary>
/// 手动拉消息
/// </summary>
/// <param name="queueName"></param>
private void ConsumePullQueue(string queueName)
{
var channel = connection.CreateModel();
var result = channel.BasicGet(queueName, false);//autoACK:false 开启手动确认
try
{
//处理消息
MessageBox.Show(Encoding.UTF8.GetString(result.Body));
//手动确认
channel.BasicAck(result.DeliveryTag, false);
}
catch
{
//退回
channel.BasicRecover(true);
}
//直接扔了
//channel.BasicReject(result.DeliveryTag, true);
//否认确认
//channel.BasicNack()
}
/// <summary>
/// 自动推消息
/// 如果多个消费者订阅一个队列,将轮询获取消息
/// </summary>
/// <param name="queueNames"></param>
private void ConsumeEventQueue(string queueName)
{
var channel = connection.CreateModel();
//开启QOS并行限制,每次发送一条,ack后再发送一条
channel.BasicQos(0, 1, false);
//通过事件订阅方式消费队列
EventingBasicConsumer consumer1 = new EventingBasicConsumer(channel);
consumer1.Received += (sender1, e1) =>
{
MessageBox.Show(Encoding.UTF8.GetString(e1.Body));
channel.BasicAck(e1.DeliveryTag, false);//手动确认
};
channel.BasicConsume(queueName, false, consumer1);//开始消费.(autoACK:false 手动确认)
}
Demo3.生产端消息确认、事务执行
//confirm确认(推荐)
using (var channel = connection.CreateModel())
{
var properties = channel.CreateBasicProperties();
properties.Persistent = true;//消息持久化
channel.ConfirmSelect();//将信道设置成confirm模式
//5:发布消息
for (int i = 0; i < 100; i++)
{
var msg = Encoding.UTF8.GetBytes($"{i}:haha");
channel.BasicPublish(exchangeName, routingKey, properties, msg);
}
bool isSuccess = channel.WaitForConfirms();//是否发布成功
}
//事务执行(低效,不推荐)
using (var channel = connection.CreateModel())
{
var properties = channel.CreateBasicProperties();
properties.Persistent = true;//消息持久化
channel.TxSelect();//将信道设置成事务模式
try
{
for (int i = 0; i < 100; i++)
{
var msg = Encoding.UTF8.GetBytes($"{i}:haha");
channel.BasicPublish(exchangeName, routingKey, properties, msg);
}
channel.TxCommit();
}
catch
{
channel.TxRollback();
}
}
参考:
https://www.rabbitmq.com/getstarted.html