package org.apache.qpid.contrib.json;

import java.io.IOException;

import org.apache.qpid.contrib.json.processer.EventProcesser;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

/**
 * 
 * 接受消息方法
 * 
 * @author 张大川
 *
 */
public class ReceiveMessageUtils {

	private Channel channel;

	private Connection connection;

	/**
	 * 
	 * @param <T>
	 * @param queueName
	 *            队列名称
	 * @param eventProcesser
	 *            处理事件实例
	 * @param clazz
	 *            要接收的消息类型
	 * @throws Exception
	 */
	public <T> void receiveMessage(String queueName, EventProcesser<T> eventProcesser, Class<T> clazz)
			throws Exception {

		channel = connection.createChannel();
		channel.queueDeclare(queueName, true, false, false, null);

		channel.basicQos(1);// 告诉RabbitMQ同一时间给一个消息给消费者

		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {

				String message = new String(body);
				boolean b = false;
				if (clazz != null) {
					eventProcesser.process((T) JSON.parseObject(message, clazz));

				} else {
					Object parse = JSON.parse(message);
					eventProcesser.process((T) parse);
				}
				b = eventProcesser.end();
				if (b) {
					channel.basicAck(envelope.getDeliveryTag(), false);
				} else {
					channel.basicNack(envelope.getDeliveryTag(), false, true);
				}
			}
		};

		channel.basicConsume(queueName, consumer);

	}

	public ReceiveMessageUtils(Connection connection) {
		super();
		this.connection = connection;
	}

	public void close() throws Exception {

		connection.close();
	}

}
@@ -1005,31 +1005,17 @@
 ;// 
-%E5%91%8A%E8%AF%89RabbitMQ%E5%90%8C%E4%B8%80%E6%97%B6%E9%97%B4%E7%BB%99%E4%B8%80%E4%B8%AA%E6%B6%88%E6%81%AF%E7%BB%99%E6%B6%88%E8%B4%B9%E8%80%85
+%E4%B8%80%E6%AC%A1%E5%8F%AA%E6%8E%A5%E6%94%B6%E4%B8%80%E4%B8%AA%E6%B6%88%E6%81%AF
 %0D%0A%0D%0A
@@ -1263,24 +1263,65 @@
 ing(body);%0D%0A
+%09%09%09%09// System.out.println(consumerTag);%0D%0A
 %09%09%09%09boolean 
@@ -1629,24 +1629,32 @@
 g(), false);
+ // %E5%8F%91%E9%80%81%E7%A1%AE%E8%AE%A4
 %0D%0A%09%09%09%09%7D else
@@ -1720,16 +1720,34 @@
 , true);
+// %E6%B6%88%E6%81%AF%E5%A4%84%E7%90%86%E5%A4%B1%E8%B4%A5%EF%BC%8C%E6%B6%88%E6%81%AF%E8%BF%94%E5%9B%9E%E9%98%9F%E5%88%97%0D%0A
 %0D%0A%09%09%09%09%7D%0D

format Signed-off-by: 张大川 <zdcxp524@sina.com>