消息发布的时候调用一下接口的时候,有个参数 mandatory
void BasicPublish(string exchange, string routingKey, bool mandatory, IBasicProperties basicProperties, byte[] body);
当mandatory设为true时,如果交换器无法根据自身类型和路由键找到一个符合条件的队列, 那么RabbitMQ会调用basicReturn命令将消息返回给生产者;当mandatory为false时,出现上述情况,则消息直接被丢弃。
此时需要消息的生产者实现
channel.BasicReturn += (model, ea) =>
{
//返回消息的处理策略
};
消息发送代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
using RabbitMQ.Client;
namespace rabbitMQPublic
{
public static class simplePublisher
{
private const string EXCHANGE_NAME = "exchange_demo";
private const string ROUTING_KEY = "routingkey_demo";
private const string QUEUE_NAME = "queue_demo";
private const string IP_ADDRESS = "127.0.0.1";
private const int PORT = 5672;//RabbitMQ 服务端默认端口5672;
private const string USER_NAME = "guest";
private const string PASSWORD = "guest";
public static void Publicer()
{
int count = 0;
int mCount = 0;
while (true)
{
IConnection con = null;
IModel channel = null;
try
{
//01.创建factory
ConnectionFactory factory = new ConnectionFactory();
factory.HostName = IP_ADDRESS;
factory.Port = PORT;
factory.UserName = USER_NAME;
factory.Password = PASSWORD;
//02.创建Connection
con = factory.CreateConnection();
//03.创建Channel
channel = con.CreateModel();
//创建一个type = "direct" 、持久化的、非自动删除的交换器
channel.ExchangeDeclare(EXCHANGE_NAME, "direct", true, false, null);
//创建一个持久的、非排他的、非自动删除的队列
channel.QueueDeclare(QUEUE_NAME, true, false, false, null);
//将交换器与队列通过路由键绑定
channel.QueueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, null);//channel.ExchangeBind()
//04.创建消息并发送
string message = "Hello Word --- " + count + " !!";
var body = Encoding.UTF8.GetBytes(message);
var properties = channel.CreateBasicProperties();
properties.Persistent = true;
channel.BasicPublish(EXCHANGE_NAME, ROUTING_KEY,true, properties, body);
channel.BasicReturn += (model, ea) =>
{
//返回消息的处理策略
};
Console.WriteLine(string.Format("mCount = {0} and Count = {1} !!", mCount, count));
System.Threading.Thread.Sleep(100);
count++;
if (count > 1000000)
{
count = 0;
mCount++;
}
}
catch (IOException ioE)
{
throw;
}
catch (SocketException socketEx)//RabbitMQ 用TCP协议,这里除了socket异常
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
//05.关闭资源
if (channel != null)
channel.Close();
if (con != null)
con.Close();
}
}//while
}
}
}
更多精彩请关注公众号:隔壁王小猿(gbwxy-happy)