public partial classRabbitMQMultithreading : Form
{public delegate void ListViewDelegate(T obj);publicRabbitMQMultithreading()
{
InitializeComponent();
}///
///ShowMessage重载///
///
private void ShowMessage(stringmsg)
{if(InvokeRequired)
{
BeginInvoke(new ListViewDelegate(ShowMessage), msg);
}else{
ListViewItem item= new ListViewItem(new string[] { DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss ffffff"), msg });
lvwMsg.Items.Insert(0, item);
}
}///
///ShowMessage重载///
///
///
private void ShowMessage(string format, params object[] args)
{if(InvokeRequired)
{
BeginInvoke(new MethodInvoker(delegate()
{
ListViewItem item= new ListViewItem(new string[] { DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss ffffff"), string.Format(format, args) });
lvwMsg.Items.Insert(0, item);
}));
}else{
ListViewItem item= new ListViewItem(new string[] { DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss ffffff"), string.Format(format, args) });
lvwMsg.Items.Insert(0, item);
}
}///
///生产者///
///
///
private void btnSend_Click(objectsender, EventArgs e)
{int messageCount = 100;var factory = newConnectionFactory
{
HostName= "192.168.2.242",
UserName= "hello",
Password= "world",
Port= AmqpTcpEndpoint.UseDefaultPort,//5672
VirtualHost = ConnectionFactory.DefaultVHost,//使用默认值:"/"
Protocol =Protocols.DefaultProtocol,
AutomaticRecoveryEnabled= true};using (var connection =factory.CreateConnection())
{using (var channel =connection.CreateModel())
{
channel.QueueDeclare(queue:"hello", durable: true, exclusive: false, autoDelete: false, arguments: null);string message = "Hello World";var body =Encoding.UTF8.GetBytes(message);for (int i = 1; i <= messageCount; i++)
{
channel.BasicPublish(exchange:"", routingKey: "hello", basicProperties: null, body: body);
ShowMessage($"Send {message}");
}
}
}
}///
///消费者///
///
///
private async void btnReceive_Click(objectsender, EventArgs e)
{
Random random= newRandom();int rallyNumber = random.Next(1, 1000);int channelCount = 0;await Task.Run(() =>{try{int asyncCount = 10;
List> tasks = new List>();var connection =RabbitMQFactory.SharedConnection;for (int i = 1; i <= asyncCount; i++)
{
tasks.Add(Task.Factory.StartNew(()=>MessageWorkItemCallback(connection, rallyNumber)));
}
Task.WaitAll(tasks.ToArray());string syncResultMsg = $"集结号 {rallyNumber} 已吹起号角--" +$"本次开启信道成功数:{tasks.Count(s => s.Result == true)}," +$"本次开启信道失败数:{tasks.Count() - tasks.Count(s => s.Result == true)}" +$"累计开启信道成功数:{channelCount + tasks.Count(s => s.Result == true)}";
ShowMessage(syncResultMsg);
}catch(Exception ex)
{
ShowMessage($"集结号 {rallyNumber} 消费异常:{ex.Message}");
}
});
}///
///异步方法///
///
///
///
private bool MessageWorkItemCallback(object state, intrallyNumber)
{bool syncResult = false;
IModel channel= null;try{
IConnection connection= state asIConnection;//不能使用using (channel = connection.CreateModel())来创建信道,让RabbitMQ自动回收channel。
channel =connection.CreateModel();
channel.QueueDeclare(queue:"hello", durable: true, exclusive: false, autoDelete: false, arguments: null);
channel.BasicQos(prefetchSize:0, prefetchCount: 1, global: false);var consumer = newEventingBasicConsumer(channel);
consumer.Received+= (model, ea) =>{var message =Encoding.UTF8.GetString(ea.Body);
Thread.Sleep(1000);
ShowMessage($"集结号 {rallyNumber} Received {message}");
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple:false);
};
channel.BasicConsume(queue:"hello", autoAck: false, consumer: consumer);
syncResult= true;
}catch(Exception ex)
{
syncResult= false;
ShowMessage(ex.Message);
}returnsyncResult;
}
}