using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mall.ThirdCore.Mq
{
    /// <summary>
    /// 消息队列帮助类
    /// </summary>
    public class RabbitMQService
    {
        /// <summary>
        /// 获取连接
        /// </summary>
        /// <param name="rabbitConfig">连接配置实体</param>
        /// <returns></returns>
        public static ConnectionFactory GetConnectionFactory(RabbitConfig rabbitConfig)
        {
            ConnectionFactory factory = new ConnectionFactory
            {
                HostName = rabbitConfig.HostName,
                //默认端口
                Port = rabbitConfig.Port,
                UserName = rabbitConfig.UserName,
                Password = rabbitConfig.Password
            };
            return factory;
        }

        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="rabbitConfig"></param>
        /// <param name="message"></param>
        public static void SendMessage(RabbitConfig rabbitConfig, string message)
        {
            using (IConnection conn = GetConnectionFactory(rabbitConfig).CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    //在MQ上定义一个持久化队列，如果名称相同不会重复创建
                    channel.QueueDeclare(rabbitConfig.QueenName, true, false, false, null);
                    byte[] buffer = Encoding.UTF8.GetBytes(message);
                    IBasicProperties properties = channel.CreateBasicProperties();
                    properties.DeliveryMode = 2;
                    channel.BasicPublish("", rabbitConfig.QueenName, properties, buffer);
                }
            }
        }

    }
}
