1、启动nameserver和broker之后(为了可视化方便还可以启动console)
2、maven依赖
org.apache.rocketmq
rocketmq-client
4.1.0-incubating
org.apache.rocketmq
rocketmq-common
4.1.0-incubating
io.netty
netty-all
4.1.36.Final
org.slf4j
slf4j-nop
1.7.2
3、生产者
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
public class ProducerMain {
public static void main(String[] args) {
//需要一个producer group名字作为构造方法的参数,这里为producer1
DefaultMQProducer producer = new DefaultMQProducer("producer1");
//设置NameServer地址,此处应改为实际NameServer地址,多个地址之间用;分隔
//NameServer的地址必须有,但是也可以通过环境变量的方式设置,不一定非得写死在代码里
producer.setNamesrvAddr("127.0.0.1:9876");
producer.setVipChannelEnabled(false);
//为避免程序启动的时候报错,添加此代码,可以让rocketMq自动创建topickey
producer.setCreateTopicKey("AUTO_CREATE_TOPIC_KEY");
try {
producer.start();
} catch (MQClientException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
try {
Message message = new Message("TopicTest", "Tag1",
("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
SendResult sendResult = producer.send(message);
System.out.println("发送的消息ID:" + sendResult.getMsgId() + "--- 发送消息的状态:" + sendResult.getSendStatus());
} catch (Exception e) {
e.printStackTrace();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
producer.shutdown();
}
}
4、消费者
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.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import java.util.List;
public class ConsumerMain {
public static void main(String[] args) {
//设置消费者组
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("CID_LRW_DEV_SUBS");
consumer.setVipChannelEnabled(false);
consumer.setNamesrvAddr("127.0.0.1:9876");
//设置消费者端消息拉取策略,表示从哪里开始消费
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
//设置消费者拉取消息的策略,*表示消费该topic下的所有消息,也可以指定tag进行消息过滤
try {
consumer.subscribe("TopicTest", "*");
} catch (MQClientException e) {
e.printStackTrace();
}
//消费者端启动消息监听,一旦生产者发送消息被监听到,就打印消息,和rabbitmq中的handlerDelivery类似
consumer.registerMessageListener(new MessageListenerConcurrently() {
public ConsumeConcurrentlyStatus consumeMessage(List msgs, ConsumeConcurrentlyContext context) {
for (MessageExt messageExt : msgs) {
String topic = messageExt.getTopic();
String tag = messageExt.getTags();
String msg = new String(messageExt.getBody());
System.out.println("*********************************");
System.out.println("消费响应:msgId : " + messageExt.getMsgId() + ", msgBody : " + msg + ", tag:" + tag + ", topic:" + topic);
System.out.println("*********************************");
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
//调用start()方法启动consumer
try {
consumer.start();
} catch (MQClientException e) {
e.printStackTrace();
}
System.out.println("Consumer Started....");
}
}
5、控制台
因为在生产者使用完之后会调用shutdown,所以在控制台是查询不到当前生产组的生产者内容;
6、报错
org.apache.rocketmq.client.exception.MQClientException: No route info of this ***
命令行手动创建Topic就好了
>mqadmin updateTopic -n localhost:9876 -b localhost:10911 -t TopicTest
7、DefaultMQPullConsumer
import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.consumer.PullResultExt;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class PullConsumer {
private static final Map offsetTable = new HashMap();
public static void main(String[] args) {
DefaultMQPullConsumer consumer = new DefaultMQPullConsumer("pullConsumer");
consumer.setNamesrvAddr("127.0.0.1:9876");
try {
consumer.start();
} catch (MQClientException e) {
e.printStackTrace();
}
try {
Set mqs = consumer.fetchSubscribeMessageQueues("TopicTest");
for(MessageQueue mq:mqs) {
System.out.println("Consume from the queue: " + mq);
// long offset = consumer.fetchConsumeOffset(mq, true);
// PullResultExt pullResult =(PullResultExt)consumer.pull(mq, null, getMessageQueueOffset(mq), 32);
//消息未到达默认是阻塞10秒,private long consumerPullTimeoutMillis = 1000 * 10;
PullResultExt pullResult = null;
try {
pullResult = (PullResultExt)consumer.pullBlockIfNotFound(mq, null, getMessageQueueOffset(mq), 32);
} catch (RemotingException e) {
e.printStackTrace();
} catch (MQBrokerException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
putMessageQueueOffset(mq, pullResult.getNextBeginOffset());
switch (pullResult.getPullStatus()) {
case FOUND:
List messageExtList = pullResult.getMsgFoundList();
for (MessageExt m : messageExtList) {
System.out.println(new String(m.getBody()));
}
break;
case NO_MATCHED_MSG:
break;
case NO_NEW_MSG:
break ;
case OFFSET_ILLEGAL:
break;
default:
break;
}
}
} catch (MQClientException e) {
e.printStackTrace();
}
}
private static void putMessageQueueOffset(MessageQueue mq, long offset) {
offsetTable.put(mq, offset);
}
private static long getMessageQueueOffset(MessageQueue mq) {
Long offset = offsetTable.get(mq);
if (offset != null)
return offset;
return 0;
}
}