RabbitMQ之(1)连接工具

package rabbitmq;

import java.io.IOException;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
 * @ClassName: RabbitMQConnection 
 * @Description: RabbitMQ连接工具
 * @author wxy 
 * @date 2019年1月24日 下午1:31:12 
 */
public class RabbitMQConnection {
	protected final Logger LOG = LogManager.getLogger(RabbitMQConnection.class);
	//是否已初始化
	private boolean isInit = false;
	//mq地址
	private String rabbitmq_url = "localhost";
	//端口号
	private int rabbitmq_port = 80;
	//用户名
	private String userName = "zxt";
	//密码
	private String password = "123456";
	//队列标识
	protected String rabbit_queue_name = "rabbit_mq_zxt";
	//连接工厂
	private ConnectionFactory connectionFactory;
	//连接
	private Connection connection;
	//渠道
	protected Channel channel;
	
	public RabbitMQConnection() {
	}

	public RabbitMQConnection(String rabbitmq_url, int rabbitmq_port, String userName, String password,
			String rabbit_queue_name) {
		LOG.info("MQ地址:" + rabbitmq_url);
		LOG.info("端口:" + rabbitmq_port);
		LOG.info("用户名:" + userName);
		LOG.info("密码:" + password);
		LOG.info("队列标识:" + rabbit_queue_name);
		this.rabbitmq_url = rabbitmq_url;
		this.rabbitmq_port = rabbitmq_port;
		this.userName = userName;
		this.password = password;
		this.rabbit_queue_name = rabbit_queue_name;
	}
	
	//初始化
	public void initConnection() {
		if(!isInit) {
			LOG.info("开始初始化");
			isInit = true;
			connectionFactory = new ConnectionFactory();
			connectionFactory.setConnectionTimeout(8000);
			connectionFactory.setHost(rabbitmq_url);
			connectionFactory.setPassword(password);
			connectionFactory.setPort(rabbitmq_port);
			connectionFactory.setUsername(userName);
			LOG.info("开始创建渠道");
			getChannel();
		}
		LOG.info("无需初始化");
	}
	
	//生成渠道
	public Channel getChannel() {
		if(null == connection) {
			try {
				//生成一个新的连接
				connection = connectionFactory.newConnection();
			} catch (Exception e) {
				e.printStackTrace();
				LOG.error(e);
			}
		}
		
		if(null == channel) {
			try {
				//通过连接生成一个新的渠道
				channel = connection.createChannel();
			} catch (Exception e) {
				LOG.error(e);
			}
		}
		
		if(null != channel) {
			try {
				channel.queueDeclare(rabbit_queue_name, true, false, false, null);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return channel;
	}
	
	//关闭渠道、连接
	public void close() {
		//关闭渠道
		if(null != channel) {
			try {
				channel.abort();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			try {
				channel.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			channel = null;
		}
		//关闭连接
		if(null != connection) {
			try {
				connection.abort();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			try {
				connection.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			connection = null;
		}
	}
	
}

你可能感兴趣的:(RabbitMQ)