package org.springblade.mq.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springblade.mq.entity.MqConf;

/**
 * title: RabbitMqConnectionUtil
 * package: com.sptg.device.api.util
 * description: RabbitMq连接工具类
 */
@Slf4j
public final class RabbitMqConnectionUtil {

    /**
     * 功能描述: 创建连接
     * @param conf 队列服务器配置
     * @return Connection
     */
    @SneakyThrows
    public static Connection openConnection(MqConf conf) {
        //建立连接和通道
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(conf.getHost());
        factory.setPort(conf.getPort());
        factory.setVirtualHost(conf.getVirtualHost());
        factory.setUsername(conf.getUsername());
        factory.setPassword(conf.getPassword());
        return factory.newConnection();
    }

    /**
     * 功能描述: 测试连接
     * @param conf 队列服务器配置
     * @return boolean
     */
    @SneakyThrows
    public static boolean testConnect(MqConf conf){
        Connection connection = null;
        try{
            connection = RabbitMqConnectionUtil.openConnection(conf);
            boolean result = connection.isOpen();
            connection.close();
            return result;
        }catch (Exception e){
            if (null != connection){
                connection.close();
            }
        }
        return false;
    }

    /**
     * 功能描述: 关闭链接
     * @param connection 连接
     */
    @SneakyThrows
    public static void closeConnection(Connection connection){
        if (null != connection) {
            connection.close();
        }
    }

    /**
     * 功能描述: 关闭管道和连接
     * @param connection 连接
     * @param channel 管道
     */
    public static void closeConnection(Connection connection, Channel channel){
        try {
            if (null != channel) {
                channel.close();
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        RabbitMqConnectionUtil.closeConnection(connection);
    }



}
