using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RabbitMQ.Client;
using RabbitMQ.ServiceModel;
using RabbitMQ.Util;
using System.Threading;
namespace rabbitMQ的使用
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
// 发送消息
private void button1_Click(object sender, EventArgs e)
{
var factory = new ConnectionFactory();
factory.HostName = "localhost";
factory.UserName = "zheng";
factory.Password = "4421707";
Task t = Task.Run(() => {
try
{
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("routKey", false, false, false, null);
var propertiies = channel.CreateBasicProperties();
propertiies.DeliveryMode = 2;
for (int i = 0; i < 10; i++)
{
var body = Encoding.UTF8.GetBytes("hello,zheng,hao,nan");
channel.BasicPublish("", "routKey", propertiies, body);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
});
}
//接收消息
private void button2_Click(object sender, EventArgs e)
{
var factory = new ConnectionFactory();
factory.HostName = "localhost";
factory.UserName = "zheng";
factory.Password = "4421707";
Task t = Task.Run(() => {
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
while (true)
{
BasicGetResult msgResponse = channel.BasicGet(queue: "routKey", noAck: true);
if (msgResponse != null)
{
string msgBody = Encoding.UTF8.GetString(msgResponse.Body);
//异步更新UI
string[] s = msgBody.Split(',');
this.Invoke((MethodInvoker)(()=>{
listBox1.Items.Add(s[0]);
listBox1.Items.Add(s[1]);
listBox1.Items.Add(s[2]+s[3]);
}));
}
}
}
}
});
}
}
}