using EasyNetQ;
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;

namespace MQTest
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            //关闭线程安全检查，关闭后可以像下面代码一样直接修改空间Text属性值，否则会报错，需要使用Invoke方法
            CheckForIllegalCrossThreadCalls = false;
        }
        private IBus bus1;
        private IBus bus2;
        private IBus bus3;
        private IBus bus4;
        private IBus bus5;
        private string connectionStr = "host=127.0.0.1;virtualHost=myvhost;username=guest;password=guest;requestedHeartbeat=10";
        private void button3_Click(object sender, EventArgs e)
        {
            bus1 = RabbitHutch.CreateBus(connectionStr);
            //发送端代码
            bus1.Send("queuename_1", new MyMessage { Text = richTextBox3.Text });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bus2 = RabbitHutch.CreateBus(connectionStr);
            //与Subscribe一样，如果在同一个队列，同一个消息类型，多次调用Receive方法时，消息会轮流发送给每个Receive端
            bus2.Receive<MyMessage>("queuename_1", message => richTextBox2.Text += message.Text + "\r\n");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bus3 = RabbitHutch.CreateBus(connectionStr);
            bus3.Receive<MyMessage>("queuename_1", message => richTextBox1.Text += message.Text + "\r\n");
        }
        private void button4_Click(object sender, EventArgs e)
        {
            bus4 = RabbitHutch.CreateBus(connectionStr);
            //发送端代码
            bus4.Send("queuename_2", new MyMessage { Text = richTextBox4.Text });
        }

        private void button5_Click(object sender, EventArgs e)
        {
            bus5 = RabbitHutch.CreateBus(connectionStr);
            bus5.Receive<MyMessage>("queuename_2", message => richTextBox5.Text += message.Text + "\r\n");
        }

        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (bus1 != null)
            {
                bus1.Dispose();
            }
            if (bus2 != null)
            {
                bus2.Dispose();
            }
            if (bus3 != null)
            {
                bus3.Dispose();
            }
            if (bus4 != null)
            {
                bus4.Dispose();
            }
            if (bus5 != null)
            {
                bus5.Dispose();
            }
        }
    }
}
