RabbitMQ 发送消息和接收消息demo
class Program
{
static void SendMsgToMQ()
{
string MonitorIp = "10.x.x.x";
int Port = 5674;
string User = "orm";
string Password = "123456";
string MonitorSendExchangName = "testSendExchange2";
string MonitorSendQueueName = "testSendQueue";
string MonitorSendServerId = "server_name";
string sendMsg = "666";
MQProxyExchangeMonitor monitorSendServerProxy = new MQProxyExchangeMonitor(MonitorIp, Port, User, Password);
monitorSendServerProxy.ExchangeDeclare(MonitorSendExchangName, ExchangeType.topic);
for(int i=0;i<0;i++)
{
sendMsg = "666";
sendMsg += i.ToString();
monitorSendServerProxy.MessageSend(System.Text.Encoding.Default.GetBytes(sendMsg), MonitorSendExchangName, MonitorSendServerId);
Thread.Sleep(3000);
}
}
static void RecvMsgFromMQ()
{
string MonitorIp = "10.x.x.x";
int Port = 5674;
string Port2 = "";
string User = "orm";
string Password = "123456";
string MonitorReceiveExchangName = "testSendExchange";
//string MonitorRecvServerId = "server_name";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Environment.CurrentDirectory + @"RabbitMQ_Config.xml");
XmlElement rootx = xmlDoc.DocumentElement;
//挨个查找其下的子节点
foreach (XmlElement childElement in rootx)
{
//分别输出子节点属性
if (childElement.OuterXml.Contains("MonitorIp"))
{
MonitorIp = childElement.GetAttribute("MonitorIp");
}
else if (childElement.OuterXml.Contains("Port"))
{
Port =int.Parse(childElement.GetAttribute("Port"));
}
else if (childElement.OuterXml.Contains("User"))
{
User = childElement.GetAttribute("User");
}
else if (childElement.OuterXml.Contains("Password"))
{
Password = childElement.GetAttribute("Password");
}
else if (childElement.OuterXml.Contains("MonitorReceiveExchangName"))
{
MonitorReceiveExchangName = childElement.GetAttribute("MonitorReceiveExchangName");
}
}
List<string> MonitorReceiveServerIds = new List<string>();
MonitorReceiveServerIds.Add("server_name");
MQProxyExchangeMonitor monitorReceiveServerProxy = new MQProxyExchangeMonitor(MonitorIp, Port, User, Password);
monitorReceiveServerProxy.ExchangeDeclare(MonitorReceiveExchangName, ExchangeType.topic);
monitorReceiveServerProxy.ExchangeMonitor(MonitorReceiveExchangName, MonitorReceiveServerIds);
monitorReceiveServerProxy.DataReceiveEvent += MonitorDataReceiveEventHandler;
}
static void MonitorDataReceiveEventHandler(DataReceiveEventArgs args)
{
Encoding utf8 = Encoding.UTF8;
string result = utf8.GetString(args.body);
UserOperationModel model2 = JsonConvert.DeserializeObject<UserOperationModel>(result);
Console.WriteLine($"body:{System.Text.Encoding.Default.GetString(args.body)} queuename:{args.queueName} exchange:{args.exchange} routingkey:{args.routingKey}");
}
static void Main(string[] args)
{
Task.Factory.StartNew(() =>
{
try
{
//SendMsgToMQ();
}
catch (Exception ex)
{
Console.WriteLine($"call SendMsgToMQ exception : {ex}");
}
});
RecvMsgFromMQ();
Console.ReadKey();
}
}