RocketMQ入门

源码和应用下载

​ 这里以RocketMQ的4.3.0版本为例,本地环境为windows10,jdk1.8, maven3.2.1.

源码下载地址: http://mirrors.hust.edu.cn/apache/rocketmq/4.3.0/rocketmq-all-4.3.0-source-release.zip

应用下载地址: https://www.apache.org/dyn/closer.cgi?path=rocketmq/4.3.0/rocketmq-all-4.3.0-bin-release.zip

启动

​ Windows下需要配置环境变量,ROCKETMQ_HOME, 我这里配置为: E:\software\rocketmq-all-4.3.0-bin-release

​ 配置完环境变量后,就可以进入到bin目录:

  • 启动server: 直接运行bin目录下的mqnamesrv.cmd

  • 启动broker: 运行mqbroker.cmd,发现一闪而过,查看bin目录下的bk.log日志,发现错误日志如下:

    错误: 找不到或无法加载主类 Files\Java\jdk1.8.0_121\lib;C:\Program

    再查看mqbroker.cmd源码,发现其最终调用了runbroker.cmd。该脚本的倒数第二行为:

    set "JAVA_OPT=%JAVA_OPT% -cp %CLASSPATH%"

    知道问题所在: CLASSPATH的配置中是包含空格的,而空格导致最终解析出来的路径错误。最终我修改倒数第二行为:

    set "JAVA_OPT=%JAVA_OPT% -cp "%CLASSPATH%""

    ​至此可以顺利启动

​ 本以为启动之后就能就行消息收发了,于是我按照官网示例进入RocketMQ的bin目录,并通过命令向broker发送消息:

tools org.apache.rocketmq.example.quickstart.Producer

​ 结果一直报错,搜索得知在windows下需要配置环境变量NAMESRV_ADDR127.0.0.1:9876

​ 配置完成之后,再依次启动mqnamesrv和mqbroker,重新测试Producer发现Producer的输出大致如下:

......
SendResult [sendStatus=SEND_OK, msgId=C0A8029D46D461BBE9BA5A115E9C03E5, offsetMsgId=C0A8130100002A9F000000000002BC96, messageQueue=MessageQueue [topic=TopicTest, brokerName=Ziyuqi-0431, queueId=0], queueOffset=249]
SendResult [sendStatus=SEND_OK, msgId=C0A8029D46D461BBE9BA5A115E9E03E6, offsetMsgId=C0A8130100002A9F000000000002BD4A, messageQueue=MessageQueue [topic=TopicTest, brokerName=Ziyuqi-0431, queueId=1], queueOffset=249]
SendResult [sendStatus=SEND_OK, msgId=C0A8029D46D461BBE9BA5A115EA003E7, offsetMsgId=C0A8130100002A9F000000000002BDFE, messageQueue=MessageQueue [topic=TopicTest, brokerName=Ziyuqi-0431, queueId=2], queueOffset=249]
11:44:47.790 [NettyClientSelector_1] INFO RocketmqRemoting - closeChannel: close the connection to remote address[192.168.19.1:10911] result: true
11:44:47.791 [NettyClientSelector_1] INFO RocketmqRemoting - closeChannel: close the connection to remote address[127.0.0.1:9876] result: true
11:44:47.793 [NettyClientSelector_1] INFO RocketmqRemoting - closeChannel: close the connection to remote address[192.168.19.1:10909] result: true

​ 在通过命令行运行Consumer:

tools org.apache.rocketmq.example.quickstart.Consumer

​ 发现Consumer的输出为:

ConsumeMessageThread_1 Receive New Messages: [MessageExt [queueId=2, storeSize=180, queueOffset=249, sysFlag=0, bornTimestamp=1537242287776, bornHost=/192.168.19.1:53847, storeTimestamp=1537242287778, storeHost=/192.168.19.1:10911, msgId=C0A8130100002A9F000000000002BDFE, commitLogOffset=179710, bodyCRC=638172955, reconsumeTimes=0, preparedTransactionOffset=0, toString()=Message{topic='TopicTest', flag=0, properties={MIN_OFFSET=0, MAX_OFFSET=250, CONSUME_START_TIME=1537242409812, UNIQ_KEY=C0A8029D46D461BBE9BA5A115EA003E7, WAIT=true, TAGS=TagA}, body=[72, 101, 108, 108, 111, 32, 82, 111, 99, 107, 101, 116, 77, 81, 32, 57, 57, 57], transactionId='null'}]]
ConsumeMessageThread_5 Receive New Messages: [MessageExt [queueId=2, storeSize=180, queueOffset=248, sysFlag=0, bornTimestamp=1537242287768, bornHost=/192.168.19.1:53847, storeTimestamp=1537242287768, storeHost=/192.168.19.1:10911, msgId=C0A8130100002A9F000000000002BB2E, commitLogOffset=178990, bodyCRC=801108784, reconsumeTimes=0, preparedTransactionOffset=0, toString()=Message{topic='TopicTest', flag=0, properties={MIN_OFFSET=0, MAX_OFFSET=250, CONSUME_START_TIME=1537242409811, UNIQ_KEY=C0A8029D46D461BBE9BA5A115E9803E3, WAIT=true, TAGS=TagA}, body=[72, 101, 108, 108, 111, 32, 82, 111, 99, 107, 101, 116, 77, 81, 32, 57, 57, 53], transactionId='null'}]]
ConsumeMessageThread_6 Receive New Messages: [MessageExt [queueId=2, storeSize=180, queueOffset=247, sysFlag=0, bornTimestamp=1537242287761, bornHost=/192.168.19.1:53847, storeTimestamp=1537242287761, storeHost=/192.168.19.1:10911, msgId=C0A8130100002A9F000000000002B85E, commitLogOffset=178270, bodyCRC=684865321, reconsumeTimes=0, preparedTransactionOffset=0, toString()=Message{topic='TopicTest', flag=0, properties={MIN_OFFSET=0, MAX_OFFSET=250, CONSUME_START_TIME=1537242409807, UNIQ_KEY=C0A8029D46D461BBE9BA5A115E9103DF, WAIT=true, TAGS=TagA}, body=[72, 101, 108, 108, 111, 32, 82, 111, 99, 107, 101, 116, 77, 81, 32, 57, 57, 49], transactionId='null'}]]
ConsumeMessageThread_2 Receive New Messages: [MessageExt [queueId=2, storeSize=180, queueOffset=246, sysFlag=0, bornTimestamp=1537242287753, bornHost=/192.168.19.1:53847, storeTimestamp=1537242287753, storeHost=/192.168.19.1:10911, msgId=C0A8130100002A9F000000000002B58E, commitLogOffset=177550, bodyCRC=1487577949, reconsumeTimes=0, preparedTransactionOffset=0, toString()=Message{topic='TopicTest', flag=0, properties={MIN_OFFSET=0, MAX_OFFSET=250, CONSUME_START_TIME=1537242409807, UNIQ_KEY=C0A8029D46D461BBE9BA5A115E8903DB, WAIT=true, TAGS=TagA}, body=[72, 101, 108, 108, 111, 32, 82, 111, 99, 107, 101, 116, 77, 81, 32, 57, 56, 55], transactionId='null'}]]

关闭

​ 关闭的步骤与启动正好相反

  • 关闭brokermqshutdown broker
  • 关闭namesrvmqshutdown namesrv

简单示例

​ 在进行简单的示例之前,我们先要知道为什么会出现RocketMQ,下面一段话摘自RocketMQ官网:

Based on our research, with increased queues and virtual topics in use, ActiveMQ IO module reaches a bottleneck. We tried our best to solve this problem through throttling, circuit breaker or degradation, but it did not work well. So we begin to focus on the popular messaging solution Kafka at that time. Unfortunately, Kafka can not meet our requirements especially in terms of low latency and high reliability, see here for details.

In this context, we decided to invent a new messaging engine to handle a broader set of use cases, ranging from traditional pub/sub scenarios to high volume real-time zero-loss tolerance transaction system. We believe this solution can be beneficial, so we would like to open source it to the community. Today, more than 100 companies are using the open source version of RocketMQ in their business. We also published a commercial distribution based on RocketMQ, a PaaS product called the Alibaba Cloud Platform.

​ 可以知道RocketMQ是阿里在使用ActiveMQ时,出现了IO瓶颈,无法满足阿里业务所需要的低延迟和高可靠性要求时自己研发出来。并且最终捐赠给Apache,成为顶级开源项目的。 high volume real-time zero-loss tolerance transaction system是其核心特点。

​ 下面通过一个简单的示例,来说明RocketMQ的基本使用:

引入pom依赖

<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.3.0</version>
</dependency>

Producer

​ Producer一般分为三种模式: 同步、异步和单向,具体代码如下:

public class SimpleProducer {
public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException,
MQBrokerException, InterruptedException {
/**
* 同步消息发送: 一般用来进行通知、短信等重要消息的同步
*/
// syncProducer(); /**
* 异步消息发送: 一般用来对方法调用响应时间有较严格要求的情况下,异步调用,立即返回
* 不同于同步的唯一在于: send方法调用的时候多携带一个回调接口参数,用来异步处理消息发送结果
*/
asyncProducer(); /**
* 单向模式: 一般用来对可靠性有一定要求的消息发送,例如日志系统
* 不同于同步的唯一之处在于: 调用的是sendOneway方法,且该方法不会给调用者任何返回值
*/
// oneWayProducer();
} private static void oneWayProducer() throws MQClientException, UnsupportedEncodingException, RemotingException, MQBrokerException, InterruptedException {
// STEP1: 创建Producer并且指定组名
DefaultMQProducer oneWayProducer = new DefaultMQProducer("GroupA"); // STEP2: 指定nameServer地址
oneWayProducer.setNamesrvAddr("localhost:9876"); // STEP3: 启动Producer
oneWayProducer.start(); // STEP4: 循环发送消息
for (int i = 0; i < 50; i++) {
Message message = new Message("OneWayTopic", "TagA",
("OneWayMsg" + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
oneWayProducer.sendOneway(message);
} // STEP5: 关闭Producer
oneWayProducer.shutdown();
} private static void asyncProducer() throws MQClientException, UnsupportedEncodingException, RemotingException, MQBrokerException, InterruptedException {
// STEP1: 创建Producer并且指定组名
DefaultMQProducer asyncProducer = new DefaultMQProducer("GroupA"); // STEP2: 指定nameServer地址
asyncProducer.setNamesrvAddr("localhost:9876"); // STEP3: 启动Producer
asyncProducer.start();
asyncProducer.setRetryTimesWhenSendAsyncFailed(0); // 设置异步发送失败重试次数,默认为2 // STEP4: 循环发送消息
for (int i = 0; i < 50; i++) {
Message message = new Message("AsyncTopic", "TagA",
("AsyncMsg" + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
// 创建回调函数处理发送成功或者异常
asyncProducer.send(message, new SendCallback() { @Override
public void onSuccess(SendResult sendResult) {
System.out.println(sendResult);
} @Override
public void onException(Throwable e) {
e.printStackTrace();
}
});
} // STEP5: 关闭Producer
TimeUnit.SECONDS.sleep(10); // 睡眠10秒,确保消息都发送出去
asyncProducer.shutdown();
} private static void syncProducer() throws MQClientException, UnsupportedEncodingException, RemotingException, MQBrokerException, InterruptedException {
// STEP1: 创建Producer并且指定组名
DefaultMQProducer syncProducer = new DefaultMQProducer("GroupA"); // STEP2: 指定nameServer地址
syncProducer.setNamesrvAddr("localhost:9876"); // STEP3: 启动Producer
syncProducer.start(); // STEP4: 循环发送消息
for (int i = 0; i < 50; i++) {
Message message = new Message("SyncTopic", "TagA",
("SyncMsg" + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
SendResult sendResult = syncProducer.send(message);
System.out.println(sendResult);
} // STEP5: 关闭Producer
syncProducer.shutdown();
}
}

Consumer

​ consumer的实现就较为简单了,定义一个事件监听接口即可.

public class SimpleConsumer {
public static void main(String[] args) throws MQClientException {
// STEP1: 创建默认Consumer并指定
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("GroupA"); // STEP2: 指定nameServer地址
consumer.setNamesrvAddr("localhost:9876"); // STEP3: 订阅对应主题和tag
consumer.subscribe("AsyncTopic", "*"); // STEP4: 注册接收到broker消息后的处理接口
consumer.registerMessageListener(new MessageListenerConcurrently() {
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
try {
System.out.println(new String(msgs.get(0).getBody(), RemotingHelper.DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
}); // STEP5: 启动consumer (必须在注册完消息监听器之后启动,否则会报错)
consumer.start(); System.out.println("Consumer started......");
}
}

总结

  • 运行Producer的时候必须保证nameServer和broker都正常运行,否则会报org.apache.rocketmq.client.exception.MQClientException: No route info of this topic
  • 即使先运行Producer只要在运行Consumer之前,未重启broker或者nameServer。Consumer启动时还是能正常收到消息

参考链接

http://rocketmq.apache.org/docs/simple-example/

RocketMQ专题1:入门的更多相关文章

  1. ActiveMQ专题1: 入门实例

    序 好久没有写博客了,最近真的是可以说是忙成狗了.项目的事和自己的终身大事忙得焦头烂额,好在是一切都是越来越好了...... 趁着项目今天唯一的一点喘息时间,加上项目开始接触到的mq,开始写一篇amq ...

  2. RocketMQ实战快速入门

    转自:https://www.jianshu.com/p/824066d70da8 一.RocketMQ 是什么      Github 上关于 RocketMQ 的介绍:RcoketMQ 是一款低延 ...

  3. rocketmq事务消息入门介绍

    说明 周五的时候发了篇:Rocketmq4.3支持事务啦!!!,趁着周末的时候把相关内容看了下,下面的主要内容就是关于RocketMQ事务相关内容介绍了. 说明: 今天这篇仅仅是入门介绍,并没有涉及到 ...

  4. RocketMQ安装及入门

    本文是作者原创,版权归作者所有.若要转载,请注明出处. 本文RocketMQ版本为rocketmq-all-4.7.0,系统为win10.请各位去官网下载,也可以留言,我发安装包 RocketMQ安装 ...

  5. Maven学习专题--Maven入门及安装

    因为项目需要,新项目需要使用Maven开发,但是组内大部分没有接触过maven.我就毅然承担搭建maven环境的任务了.因为一切重头开始,就想把自己的整个搭建环境.项目创建.框架整合和模块管理整个过程 ...

  6. RocketMQ专题2:三种常用生产消费方式(顺序、广播、定时)以及顺序消费源码探究

    顺序.广播.定时任务 前插 ​ 在进行常用的三种消息类型例子展示的时候,我们先来说一说RocketMQ的几个重要概念: PullConsumer与PushConsumer:主要区别在于Pull与Pus ...

  7. RocketMQ—消息队列入门

    消息队列功能介绍 字面上说的消息队列是数据结构中"先进先出"的一种数据结构,但是如果要求消除单点故障,保证消息传输可靠性,应对大流量的冲击,对消息队列的要求就很高了.现在互联网的& ...

  8. docker专题 从入门到放弃

    1.docker是什么 Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的镜像中,然后发布到任何流行的 Linux或Windows操作系统的机器上,也可以实现虚 ...

  9. ActiveMQ从入门到精通(二)

    接上一篇<ActiveMQ从入门到精通(一)>,本篇主要讨论的话题是:消息的顺序消费.JMS Selectors.消息的同步/异步接受方式.Message.P2P/PubSub.持久化订阅 ...

随机推荐

  1. Handle( )

    Handle( ) //得到PB窗口型对象的句柄 功  能:得到PB窗口型对象的句柄.使用该函数可以得到应用对象.窗口或控件的句柄,但不能得到绘图对象的句柄. 语  法:Handle ( object ...

  2. CxGrid鼠标移到更改颜色

    CxGrid鼠标移到更改颜色 设置表单中TcxGrid1DBTableView的Styles属性,设置Selection procedure TForm1.cxGrid1DBTableView1Mou ...

  3. 用 select 语句实现递归的方法

    with Test_Recursion(Id,ParentId)AS(select Id,ParentId  from [V_KPI_DetailsActivities] where ParentId ...

  4. Excel 多个单元格输入同样内容

    step1: 将这些单元格选定.方法:可以连续选,也可以 ctrl + select不连续选择: step2:输入你想输入的内容,PS:出现在最后选择的单元格中: step3:组合键:ctrl + e ...

  5. 如何获取 docker 容器(container)的 ip 地址

    1. 进入容器内部后 cat /etc/hosts 会显示自己以及(– link)软连接的容器IP 2.使用命令 docker inspect --format '{{ .NetworkSetting ...

  6. powerviot open error in sharepoint 2013

    Testing Service c2WTS +- Service c2WTS found +- Service c2WTS is running +- Path of service: C:\Prog ...

  7. 一起做OJ-环境搭建

    这几天,看到OJ火了起来,尤其是OnlineJudge(QingDaoU)和HUSTOJ. 作为正在花大力研究PHP和Bootstrap的我,看到了,当然不会甘心. 于是,我决定把学到的知识用在编写O ...

  8. API网关【gateway 】- 1

    最近在公司进行API网关重写,公司内采用serverMesh进行服务注册,调用,这里结合之前学习对API网关服务进行简单的总结与分析. 网关的单节点场景: 网关的多节点场景: 这里的多节点是根据模块进 ...

  9. C# MemoryStream BinaryReader

    不清楚这类东西内部搞什么鬼,直接看代码才舒爽 https://referencesource.microsoft.com/#mscorlib 然后可以在线测试 https://www.tutorial ...

  10. Servlet各种路径、URL配置分析

    大家都知道,Servlet有个配置: <servlet> <servlet-name>zolltyMVC</servlet-name> <servlet-cl ...