RabbitMQ之(3)接收端

package rabbitmq;

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

import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;
/**
 * @ClassName: RabbitMQReceive 
 * @Description: RabbitMQ接收端
 * @author wxy 
 * @date 2019年1月24日 下午1:30:18 
 */
public class RabbitMQReceive extends RabbitMQConnection implements Runnable{
	protected final Logger LOG = LogManager.getLogger(RabbitMQReceive.class);
	//消费者
	private QueueingConsumer consumer;
	//消息监听者
	private RabbitMQListener listener;
	
	public RabbitMQReceive(RabbitMQListener listener) {
		super();
		this.listener = listener;
		this.init();
	}
	
	public RabbitMQReceive(String rabbitmq_url, int rabbitmq_port, String userName, String password,
			String rabbit_queue_name, RabbitMQListener listener) {
		super(rabbitmq_url, rabbitmq_port, userName, password, rabbit_queue_name);
		this.listener = listener;
		this.init();
	}
	
	public void init() {
		super.initConnection();
		getReceive();
	}
	
	public void getReceive() {
		LOG.info("启动接收端线程");
		new Thread(this).start();
	}
	
	@Override
	public void run() {
		while(true) {
			if(null != listener) {
				if(null == consumer) {
					try {
						consumer = new QueueingConsumer(channel);
						channel.basicConsume(rabbit_queue_name, true, consumer);
					} catch (Exception e) {
						LOG.error(e);
						if(null != consumer) {
							consumer = null;
						}
					}
				}
				
				try {
					QueueingConsumer.Delivery delivery = consumer.nextDelivery();
					if(null == listener) {
						listener = new TestListener();
					}
					listener.receiveMessage(new String(delivery.getBody()));
				} catch (ShutdownSignalException e) {
					e.printStackTrace();
				} catch (ConsumerCancelledException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch(Exception e) {
					LOG.error(e);
					this.close();
					if(null != channel) {
						channel = null;
					}
					getChannel();
				}
			}
			
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private class TestListener implements RabbitMQListener {
		
		public TestListener(){
		}
		
		@Override
		public void receiveMessage(String message) {
			LOG.info("接收消息:" + message);
		}
		
	}
	
	public static void main(String[] args) {
		RabbitMQReceive receive = new RabbitMQReceive(null);
		receive.init();
		receive.getReceive();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值