All Downloads are FREE. Search and download functionalities are using the official Maven repository.

arp.message.rocketmq.RocketmgMessageReceiver Maven / Gradle / Ivy

There is a newer version: 1.0.3
Show newest version
package arp.message.rocketmq;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import arp.process.publish.Message;
import arp.process.publish.ProcessMessageReceiver;

public class RocketmgMessageReceiver implements ProcessMessageReceiver {
	private DefaultMQPushConsumer consumer;
	private ConcurrentLinkedQueue messageQueue;

	public RocketmgMessageReceiver(String consumerGroup, String namesrvAddr)
			throws MQClientException {
		this(consumerGroup, namesrvAddr, new FSTDeserializationStrategy());
	}

	public RocketmgMessageReceiver(String consumerGroup, String namesrvAddr,
			RocketmqMessageDeserializationStrategy deserializationStrategy)
			throws MQClientException {
		messageQueue = new ConcurrentLinkedQueue<>();
		// 实例化消费者
		consumer = new DefaultMQPushConsumer(consumerGroup);
		// 设置NameServer的地址
		consumer.setNamesrvAddr(namesrvAddr);
		consumer.subscribe("arp_process_message", "*");
		// 注册回调实现类来处理从broker拉取回来的消息
		consumer.registerMessageListener(new MessageListenerConcurrently() {
			@Override
			public ConsumeConcurrentlyStatus consumeMessage(
					List msgs, ConsumeConcurrentlyContext context) {
				if (msgs != null) {
					for (MessageExt msg : msgs) {
						try {
							messageQueue.offer(deserializationStrategy
									.deserialize(msg.getBody()));
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				}
				// 标记该消息已经被成功消费
				return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
			}
		});
		// 启动消费者实例
		consumer.start();
	}

	@Override
	public List receive() throws Exception {
		List msgLst = new ArrayList<>();
		int size = messageQueue.size();
		for (int i = 0; i < size; i++) {
			msgLst.add(messageQueue.poll());
		}
		return msgLst;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy