using Mall.Common.Models;
using RabbitMQ.Client;
using System;
using System.Text;

namespace Mall.Common.Plugin
{
    /// <summary>
    /// RabbitMq消息队列
    /// </summary>
    public class RabbiMQManager
    {
        /// <summary>
        /// 获取连接
        /// </summary>
        /// <param name="rabbitConfig">连接配置实体</param>
        /// <returns></returns>
        private 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);
                }
            }
        }
    }
}
